package com.xhwl.data.service.impl.personal;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.xhwl.common.dto.cent.face.AddFaceDTO;
import com.xhwl.common.dto.cent.face.DelFaceDTO;
import com.xhwl.common.dto.cent.face.QueryFaceDTO;
import com.xhwl.common.dto.cent.sdata.OrganizationDTO;
import com.xhwl.common.dto.cent.sdata.PermissionGroupDTO;
import com.xhwl.common.dto.cent.sdata.space.ProjectSpaceDTO;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.enums.CredentialsEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.config.BusinessType;
import com.xhwl.common.enums.config.RoleTypeEnum;
import com.xhwl.common.enums.healthaged.EducationLevelEnum;
import com.xhwl.common.enums.healthaged.NationTypeEnum;
import com.xhwl.common.enums.healthaged.PoliticalOutlookEnum;
import com.xhwl.common.enums.personal.StaffStateEnum;
import com.xhwl.common.enums.personal.StaffTypeEnum;
import com.xhwl.common.enums.sdata.EnterpriseTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.pojo.cent.sdata.personnel.*;
import com.xhwl.common.query.cent.sdata.*;
import com.xhwl.common.vo.cent.face.DelFaceListVO;
import com.xhwl.common.vo.cent.face.QueryFaceVO;
import com.xhwl.data.dao.IAccountDao;
import com.xhwl.data.dao.IProjectDao;
import com.xhwl.data.dao.personal.*;
import com.xhwl.data.mq.producer.StaffProducer;
import com.xhwl.data.pojo.personal.StaffFieldMap;
import com.xhwl.data.service.*;
import com.xhwl.data.service.face.IFaceProjectLibraryCentService;
import com.xhwl.data.service.personal.*;
import com.xhwl.data.util.SpringContextUtils;
import com.xhwl.data.util.ValidatorUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 16:06 2022/2/8
 */
@Service
public class StaffServiceImpl extends ServiceImpl<IStaffDao, Staff> implements IStaffService {

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IStaffDao staffDao;

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private IStaffOrganizationService staffOrganizationService;

    @Autowired
    private IAccountOrganizationService accountOrganizationService;

    @Autowired
    private IAccountProjectService accountProjectService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IAccountRoleService accountRoleService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IAccountDeleteLogService accountDeleteLogService;

    @Autowired
    private IFaceManageService faceManageService;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    @Autowired
    private IStaffExtraDao staffExtraDao;

    @Autowired
    private IStaffBusinessTypeDao businessTypeDao;

    @Autowired
    private IProjectDao projectDao;

    @Autowired
    private IStaffBusinessRelationService staffBusinessRelationService;

    @Autowired
    private IStaffBusinessRelationDao staffBusinessRelationDao;

    @Autowired
    private StaffProducer staffProducer;

    @Autowired
    private IPermissionGroupService permissionGroupService;

    @Autowired
    private IFaceCentService faceCentService;

    @Autowired
    private IOrganizationManagerService organizationManagerService;

    @Autowired
    private IStaffOrganizationDao staffOrganizationDao;

    @Autowired
    private IFaceProjectLibraryCentService faceProjectLibraryCentService;

    private static final Logger log = LoggerFactory.getLogger(StaffServiceImpl.class);

    @Autowired
    private IStaffAuditRecordService staffAuditRecordService;

    @Autowired
    private IEnterpriseExtraService enterpriseExtraService;

    private static final String OPERATOR_REVIEW_ATTRIBUTE = "reviewChildrenStaff";

    @Autowired
    private IEnterpriseSpaceService enterpriseSpaceService;

    @Autowired
    private IStaffBusinessTypeService staffBusinessTypeService;

    @Autowired
    private IStaffExtraService staffExtraService;

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;


    @Autowired
    private IStaffCertificateService staffCertificateService;

    //员工离职主题
    private static String DELETE_TOPIC="cent-data-staff-delete";

    private static final String STAFF_ROLE_CODE = "COMPANY_COMMON_STAFF";

    private static final String TOURIST_ROLE_CODE = "TOURIST1";


    @Override
    @Transactional
    public ResultJson create(StaffDTO staffDTO, Account operator) {
        ResultJson resultJson1 = staffCheck(staffDTO, operator, false);
        if (!resultJson1.getState()) {
            return resultJson1;
        }
        dataConvert(staffDTO);
        Account account1 = accountService.phoneExistV2(staffDTO.getPhone(), operator.getDevelopId());
        if (null != account1) {
            //绑定账号
            return bind(staffDTO,operator);
        }
        // 创建帐号
        Account account = new Account();
        BeanUtils.copyProperties(staffDTO, account);
        // 设置帐号创建的业态信息（非必须）
        if (null == account.getIndustryId()) {
            account.setIndustryId(operator.getIndustryId());
        }
        // 账号设置身份证号码
        if (CredentialsEnum.ID_CARD == staffDTO.getCardType()) {
            account.setIdCard(staffDTO.getCardNo());
        }
        ResultJson<Integer> resultJson = accountService.createAccountV2(account, accountRelationWrapper(staffDTO), staffDTO.getPermissionGroupDTOs());
        if (!resultJson.getState()) {
            return resultJson;
        }
        // 保存员工信息 和 业务类型的关系
        Staff staff = saveStaff(staffDTO, resultJson.getResult());
        //保存人脸到人脸库
        if (null != staffDTO.getProjectId()){
            if (StringUtils.isNotEmpty(staffDTO.getFaceUrl())) {
                ResultJson resultJson2 = saveFace(staff.getAccountId(), staffDTO);
                //同步失败则不保存到数据库
                if (!resultJson2.getState() || CodeEnum.SUCCESS.code != resultJson.getCode()) {
                    return resultJson2;
                }
            }
        }
        //保存证书附件
        if (null != staffDTO.getCertificate() && staffDTO.getCertificate().size() != 0){
            List<StaffCertificate> staffCertificateList = new ArrayList<>();
            for (int i = 0; i < staffDTO.getCertificate().size(); i++) {
                StaffCertificate certificate = staffDTO.getCertificate().get(i);
                certificate.setStaffId(staff.getId());
                staffCertificateList.add(certificate);
            }
            if (staffCertificateList.size() > 0){
                staffCertificateService.saveBatch(staffCertificateList);
            }
        }
        // 保存组织信息
        saveOrganization(staffDTO, account, staff);
        // 空间信息
        updateAccountOrganization(staff.getAccountId(), staffDTO.getSpaceIds(),staffDTO.getEnterpriseId().get(0));
        staffDTO.setAccountId(account.getId());
        staffDTO.setId(staff.getId());
        // 保存自定义字段
        saveStaffExtra(staffDTO);
        try {
            staffProducer.create(staffDTO);
        } catch (Exception e) {
            log.info("当前员工数据推送到新增主题异常,员工数据={}", staffDTO);
        }
        return ResultJson.success("操作成功", staffDTO);
    }

    /**
     * 角色 企业 项目封装
     * @param staffDTO
     * @return
     */
    private AccountRelation accountRelationWrapper(StaffDTO staffDTO){
        AccountRelation accountRelation = new AccountRelation();
        accountRelation.setRoleIds(staffDTO.getRoleIds());
        accountRelation.setEnterpriseIds(staffDTO.getEnterpriseId());
        accountRelation.setProjectIds(staffDTO.getProjectIds());
        accountRelation.setCurrentIndustryId(staffDTO.getCurrentIndustryId());
        return accountRelation;
    }

    private void dataConvert(StaffDTO staffDTO) {
        if (null != staffDTO.getPoliticsStatusId()) {
            staffDTO.setPoliticsStatus(PoliticalOutlookEnum.findEnumByCode(staffDTO.getPoliticsStatusId()));
        }
        if (null != staffDTO.getNationId()) {
            staffDTO.setNation(NationTypeEnum.findEnumByCode(staffDTO.getNationId()));
        }
        if (null != staffDTO.getEducationalLevelId()) {
            staffDTO.setEducationalLevel(EducationLevelEnum.findEnumByCode(staffDTO.getEducationalLevelId()));
        }
    }

    private void saveStaffExtra(StaffDTO staffDTO) {
        if (null == staffDTO.getStaffExtra()) {
            QueryWrapper<StaffExtra> staffExtraQueryWrapper = new QueryWrapper<>();
            staffExtraQueryWrapper.eq("staff_id", staffDTO.getId());
            staffExtraDao.delete(staffExtraQueryWrapper);
            return;
        }
        // 更新
        if (null != staffDTO.getStaffExtra().getId()) {
            staffExtraDao.updateById(staffDTO.getStaffExtra());
        } else {
            QueryWrapper<StaffExtra> staffExtraQueryWrapper = new QueryWrapper<>();
            staffExtraQueryWrapper.eq("staff_id", staffDTO.getId());
            List<StaffExtra> staffExtras = staffExtraDao.selectList(staffExtraQueryWrapper);
            if (CollectionUtils.isNotEmpty(staffExtras)) {
                log.error("员工的扩展信息已存在，只能更新");
                throw new DataException("员工的扩展信息已存在，只能更新");
            }
            StaffExtra staffExtra = staffDTO.getStaffExtra();
            staffExtra.setStaffId(staffDTO.getId());
            staffExtraDao.insert(staffExtra);
        }
    }

    private ResultJson saveFace(Integer userId, StaffDTO staffDTO) {
        AddFaceDTO addFaceDTO = new AddFaceDTO();
        addFaceDTO.setImage(staffDTO.getFaceUrl());
        addFaceDTO.setAccountId(userId);
        addFaceDTO.setProjectId(staffDTO.getProjectId());
        addFaceDTO.setSex(staffDTO.getSex());
        addFaceDTO.setIdentification(staffDTO.getCardNo());
        addFaceDTO.setPhone(staffDTO.getPhone());
        addFaceDTO.setUsername(staffDTO.getLoginName());
        ResultJson<QueryFaceVO> resultJson = faceCentService.addingAcquaintanceFace(addFaceDTO);
        if (!resultJson.getState() || CodeEnum.SUCCESS.code != resultJson.getCode()) {
            log.warn("人脸同步失败");
            return resultJson;
        }
        return ResultJson.success("人脸同步成功");
    }

    private ResultJson deleteFace(Integer userId, Integer projectId){
        Account account = accountService.findById(userId);
        DelFaceDTO delFaceDTO = new DelFaceDTO();
        delFaceDTO.setAccountId(account.getId());
        delFaceDTO.setProjectId(projectId);
        ResultJson<DelFaceListVO> resultJson = faceCentService.deleteAccountFace(delFaceDTO);
        if (!resultJson.getState() || CodeEnum.SUCCESS.code != resultJson.getCode()){
            log.warn("人脸删除同步失败");
        }
        return ResultJson.success("人脸同步成功");
    }

    @Override
    @Transactional
    public ResultJson edit(StaffDTO staffDTO, Account operator) {
        if (null == staffDTO.getId()) {
            return ResultJson.fail("参数错误");
        }
        ResultJson resultJson1 = staffCheck(staffDTO, operator, false);
        if (!resultJson1.getState()) {
            return resultJson1;
        }
        dataConvert(staffDTO);
        //保存人脸到人脸库
            try {
               if (null != staffDTO.getProjectId()){
                   String faceUrl = accountService.findById(staffDTO.getAccountId()).getFaceUrl();
                   if (StringUtils.isNotEmpty(staffDTO.getFaceUrl())) {
                       if (!faceUrl.equals(staffDTO.getFaceUrl())) {
                           ResultJson resultJson = saveFace(staffDTO.getAccountId(), staffDTO);
                           if ( !resultJson.getState() || CodeEnum.SUCCESS.code != resultJson.getCode()) {
                               return resultJson;
                           }
                       }
                   }
                   else {
                       deleteFace(staffDTO.getAccountId(),staffDTO.getProjectId());
                   }
               }
            } catch (Exception e) {
                e.printStackTrace();
            }

        Staff staff = staffDao.selectById(staffDTO.getId());
        Account account = new Account();
        BeanUtils.copyProperties(staffDTO, account);
        account.setId(staff.getAccountId());
        // 账号设置身份证号码
        if (CredentialsEnum.ID_CARD.equals(staffDTO.getCardType())) {
            account.setIdCard(staffDTO.getCardNo());
        } else {
            account.setIdCard("");
        }
        ResultJson resultJson = accountService.updateAccountV2(operator, account, accountRelationWrapper(staffDTO), staffDTO.getPermissionGroupDTOs());
        if (!resultJson.getState()) {
            return resultJson;
        }
        // 更新空间权限
        updateAccountOrganization(staff.getAccountId(), staffDTO.getSpaceIds(),staffDTO.getEnterpriseId().get(0));
        saveStaff(staffDTO, account.getId());
        saveOrganization(staffDTO, account, new Staff(staffDTO.getId()));
        saveStaffExtra(staffDTO);

        //更新员工证书附件(先删除后插入)
        QueryWrapper<StaffCertificate> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("certificate_url").eq("staff_id",staffDTO.getId());
        List<StaffCertificate> staffCertificates = staffCertificateService.list(queryWrapper);
        //删除证书附件
        if (null != staffCertificates){
            QueryWrapper<StaffCertificate> queryCertificateDelete = new QueryWrapper<>();
            queryCertificateDelete.eq("staff_id",staffDTO.getId());
            staffCertificateService.remove(queryCertificateDelete);
        }
        //保存最新证书附件
        if (null != staffDTO.getCertificate() && staffDTO.getCertificate().size() != 0){
            List<StaffCertificate> staffCertificateList = new ArrayList<>();
            for (int i = 0; i < staffDTO.getCertificate().size(); i++) {
                StaffCertificate certificate = staffDTO.getCertificate().get(i);
                certificate.setStaffId(staffDTO.getId());
                staffCertificateList.add(certificate);
            }
            if (staffCertificateList.size() > 0){
                staffCertificateService.saveBatch(staffCertificateList);
            }
        }
        try {
            staffProducer.update(staffDTO);
        } catch (Exception e) {
            log.info("当前员工数据推送到更新主题异常,员工数据={}", staffDTO);
        }
        return ResultJson.success();
    }

    private void updateAccountOrganization(Integer accountId, List<Integer> spaceIds, Integer entId) {
        List<Integer> integers = organizationTypeService.spaceIds();
        // 先删后增
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.in("type", integers);
        accountOrganizationQueryWrapper.eq("account_id", accountId);
        accountOrganizationService.remove(accountOrganizationQueryWrapper);
        if (CollectionUtils.isEmpty(spaceIds)) {
            return;
        }
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.withIds(spaceIds);
        organizationQuery.setTypes(integers);
        List<Organization> organizations = organizationService.list(organizationQuery);
        if (CollectionUtils.isNotEmpty(organizations)) {
            List<AccountOrganization> accountOrganizations = new ArrayList<>(organizations.size());
            for (Organization organization : organizations) {
                AccountOrganization accountOrganization = new AccountOrganization();
                accountOrganization.setType(organization.getType());
                accountOrganization.setAccountId(accountId);
                accountOrganization.setOrganizationId(organization.getId());
                accountOrganization.setEnterpriseId(entId);
                accountOrganizations.add(accountOrganization);
            }
            accountOrganizationService.saveBatch(accountOrganizations);
        }
    }


    @Override
    public Page<StaffDTO> page(StaffQuery staffQuery, Page page) {
        // 查询下级组织
        if (!staffQuery.isShowCurrent()) {
            getChildOrg(staffQuery);
        }
        long cu = System.currentTimeMillis();
        Page<StaffDTO> page1 = staffDao.page(page, staffQuery);
        log.info("spend {}", (System.currentTimeMillis() - cu));
        long l = System.currentTimeMillis();
        accountInfoSetter(page1.getRecords());
        log.info("spend 2 {}", (System.currentTimeMillis() - l));
        baseDataSetter(staffQuery, page1.getRecords());
        return page1;
    }



    @Override
    public Page<StaffDTO> pageAll(StaffQuery staffQuery, Page page) {
        // 查询下级组织
        if (!staffQuery.isShowCurrent()) {
            getChildOrg(staffQuery);
        }
        long cu = System.currentTimeMillis();
        Page<StaffDTO> page1 = staffDao.pageAll(page, staffQuery);
        log.info("spend {}", (System.currentTimeMillis() - cu));
        long l = System.currentTimeMillis();
        accountInfoSetter(page1.getRecords());
        log.info("spend 2 {}", (System.currentTimeMillis() - l));
        baseDataSetter(staffQuery, page1.getRecords());
        return page1;
    }

    @Override
    public List<Integer> pageAllAccountId(StaffQuery staffQuery) {
        List<Integer> pageAccountIds = staffDao.pageAllAccountId(staffQuery);
        return pageAccountIds;
    }

    private void baseDataSetter(StaffQuery staffQuery, List<StaffDTO> records) {
        Organization organization = organizationService.getById(staffQuery.getOrgId());
        Integer level = null;
        if (null != organization){
            level = organization.getLevel();
        }
        // 回填员工的组织信息，角色信息，项目信息, 岗位信息，       政治面貌，民族，学历，业务类型，上级名称，证件类型，  自定义字段信息
        if(!records.isEmpty()){
            StaffFieldMap staffFieldMap = staffFieldViewHandler(records);
            //获取当前登录操作账号的角色身份
            for (StaffDTO record : records) {
                record.setProjectNames(staffFieldMap.getProjectMap().get(record.getAccountId()));
                List<Project> projects = staffFieldMap.getProjectAllMap().get(record.getAccountId());
                if (CollectionUtils.isNotEmpty(projects)){
                    record.setProjectIds(projects.stream().map(Project::getId).collect(Collectors.toList()));
                }
                record.setRoleNames(staffFieldMap.getRoleMap().get(record.getAccountId()));
                List<Organization> organizations = staffFieldMap.getDeptMap().get(record.getId());
                if(!CollectionUtils.isEmpty(organizations)) {
                    organizations.removeAll(Collections.singletonList(null));
                    if (!CollectionUtils.isEmpty(organizations)) {
                        record.setOrganizations(organizations);
                        record.setOrgNames(organizations.stream().map(i -> i.getName()).collect(Collectors.toList()));
                        record.setOrgIds(organizations.stream().map(i -> i.getId()).collect(Collectors.toList()));
                    }
                }
                //level不等于1（不是根节点）
                if (null != level && level != 1){
                    List<OrganizationManager> organizationManagers = staffFieldMap.getManagerMap().get(record.getAccountId());
                    if (CollectionUtils.isNotEmpty(organizationManagers)){
                        List<Integer> managerIds = organizationManagers.stream().map(i -> i.getOrgId()).collect(Collectors.toList());
                        if (managerIds.contains(staffQuery.getOrgId())){
                            record.setIsManager(true);
                        }
                    }
                }
                List<Enterprise> enterprises = staffFieldMap.getEnterpriseMap().get(record.getId());
                if (CollectionUtils.isNotEmpty(enterprises)){
                    enterprises.removeAll(Collections.singletonList(null));
                    if (CollectionUtils.isNotEmpty(enterprises)){
                        record.setEnterpriseId(enterprises.stream().map(i->i.getId()).collect(Collectors.toList()));
                        record.setEnterpriseNames(enterprises.stream().map(i->i.getName()).collect(Collectors.toList()));
                    }
                }
                if(null != record.getStaffType()){
                    record.setStaffTypeName(StaffTypeEnum.idOf(record.getStaffType()));
                }
                if(null != record.getStaffState()){
                    record.setStaffStateName(StaffStateEnum.idOf(record.getStaffState()));
                }
                if(null != record.getPositionId()){
                    record.setPositionName(staffFieldMap.getPositionMap().get(record.getPositionId()));
                }
                // 政治面貌
                if(null != record.getPoliticsStatus()){
                    record.setPoliticsStatusName(record.getPoliticsStatus().name);
                }
                // 民族
                if(null != record.getNation()){
                    record.setNationName(record.getNation().name);
                }
                // 学历
                if(null != record.getEducationalLevel()){
                    record.setEducationalLevelName(record.getEducationalLevel().name);
                }
                if(null != record.getCardType()){
                    record.setCardTypeName(record.getCardType().getDescription());
                }
                if(null != record.getHigherUp()){
                    record.setHigherUpName(staffFieldMap.getUpNameMap().get(record.getHigherUp()));
                }
                // 设置拓展信息
                record.setStaffExtra(staffFieldMap.getExtraMap().get(record.getId()));
                // 填充参加工作时间
                if (null != record.getWorkingTime()) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    record.setWorkingTimeShow(simpleDateFormat.format(record.getWorkingTime()));
                }
            }
        }
    }


    /**
     * 回显字段统一处理
     * @param records
     * @return
     */
    @Override
    public StaffFieldMap staffFieldViewHandler(List<StaffDTO> records){
        StaffFieldMap staffFieldMap = new StaffFieldMap();
        List<Integer> upNames = new ArrayList<>();
        List<Integer> positionIds = new ArrayList<>();
        for (StaffDTO record : records) {
            if(null != record.getHigherUp()){
                upNames.add(record.getHigherUp());
            }
            if(null != record.getPositionId()){
                positionIds.add(record.getPositionId());
            }
        }
        List<Integer> staffIds = records.stream().map(i -> i.getId()).collect(Collectors.toList());
        staffFieldMap.setProjectMap(this.findProjectMap(staffIds));
        List<Integer> accountIds = records.stream().map(i -> i.getAccountId()).collect(Collectors.toList());
        staffFieldMap.setProjectAllMap(this.findProjectAllMap(accountIds));
        Map<Integer, List<String>> roleInfo =  this.findRoleMap(accountIds);
        staffFieldMap.setRoleMap(roleInfo);
        staffFieldMap.setEnterpriseMap(this.findEnterpriseMap(staffIds));
        Map<Integer, List<Organization>> deptInfo = this.findDeptAllEntityMap(staffIds);
        staffFieldMap.setDeptMap(deptInfo);
        Map<Integer,List<PermissionGroup>> permissionInfo = this.findPermissionMap(accountIds);
        permissionHandler(permissionInfo,staffFieldMap);
        extraInfoHandler(staffIds, staffFieldMap);
        managerHandler(accountIds, staffFieldMap);
        positionHandler(positionIds, staffFieldMap);
        // 处理业务类型直接放到records里面了
        staffBusinessTypeHandler(records, staffIds);
        higherUpHandler(upNames, staffFieldMap);
        // 空间权限
//        spaceViewHandler(accountIds, staffFieldMap);
        return staffFieldMap;
    }

    private Map<Integer, List<Project>> findProjectAllMap(List<Integer> accountId) {
        QueryWrapper<AccountProject> accountProjectQueryWrapper = new QueryWrapper<>();
        accountProjectQueryWrapper.in("account_id", accountId);
        List<AccountProject> accountProjects = accountProjectService.list(accountProjectQueryWrapper);
        if (accountProjects.isEmpty()) {
            log.warn("帐号暂未关联项目信息");
            return Collections.emptyMap();
        }
        List<Integer> projectIds = accountProjects.stream().map(i -> i.getProjectId()).distinct().collect(Collectors.toList());
        Map<Integer, List<Integer>> accountProjectMap = accountProjects.stream().filter(i -> null != i.getProjectId()).collect(Collectors.groupingBy(AccountProject::getAccountId, Collectors.mapping(AccountProject::getProjectId, Collectors.toList())));
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.setIds(projectIds);
        List<Project> project = projectService.list(projectQuery, null);
        if (project.isEmpty()) {
            log.warn("项目信息不存在");
            return Collections.emptyMap();
        }
        Map<Integer, List<Project>> result = new HashMap<>();
        for (Map.Entry<Integer, List<Integer>> integerListEntry : accountProjectMap.entrySet()) {
            List<Integer> value = integerListEntry.getValue();
            List<Project> projects = project.stream().filter(i -> value.contains(i.getId())).collect(Collectors.toList());
            result.put(integerListEntry.getKey(), projects);
        }
        return result;
    }

    private Map<Integer, List<Enterprise>> findEnterpriseMap(List<Integer> staffIds) {
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.in("staff_id", staffIds);
        List<StaffOrganization> staffOrganizations = staffOrganizationService.list(staffOrganizationQueryWrapper);
        if (staffOrganizations.isEmpty()) {
            log.warn("帐号暂未关联企业信息");
            return Collections.emptyMap();
        }
        List<Integer> enterpriseIds = staffOrganizations.stream().map(i -> i.getEnterpriseId()).distinct().collect(Collectors.toList());
        Map<Integer, List<Integer>> staffOrgMap = staffOrganizations.stream().filter(i -> null != i.getEnterpriseId()).collect(Collectors.groupingBy(StaffOrganization::getStaffId, Collectors.mapping(StaffOrganization::getEnterpriseId, Collectors.toList())));
        EnterpriseQuery enterpriseQuery = new EnterpriseQuery();
        enterpriseQuery.setIdList(enterpriseIds);
        List<Enterprise> enterprises = enterpriseService.list(enterpriseQuery, null);
        if (enterprises.isEmpty()) {
            log.warn("企业信息不存在");
            return Collections.emptyMap();
        }
        Map<Integer,Enterprise> enterpriseMap = enterprises.stream().collect(Collectors.toMap(Enterprise::getId,enterprise -> enterprise));
        Map<Integer, List<Enterprise>> result = new HashMap<>(staffOrgMap.size());
        for (Map.Entry<Integer, List<Integer>> integerListEntry : staffOrgMap.entrySet()) {
            List<Integer> value = integerListEntry.getValue();
            List<Enterprise> enterprisesList = value.stream().map(i -> enterpriseMap.get(i)).collect(Collectors.toList());
            result.put(integerListEntry.getKey(), enterprisesList);
        }
        return result;
    }

    /**
     * 上级信息
     */
    private void higherUpHandler(List<Integer> upNames, StaffFieldMap staffFieldMap){
        Map<Integer, String> upNameMap = new HashMap<>();
        if(!upNames.isEmpty()){
            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.select("id", "name");
            accountQueryWrapper.in("id", upNames);
            List<Account> list = accountService.list(accountQueryWrapper);
            if(!list.isEmpty()){
                upNameMap = list.stream().collect(Collectors.toMap(Account::getId, Account::getName));
                staffFieldMap.setUpNameMap(upNameMap);
            }
        }
    }

    /**
     * 组织负责人
     */
    private void managerHandler(List<Integer> accountIds,StaffFieldMap staffFieldMap){
        Map<Integer, List<OrganizationManager>> managerMap = new HashMap<>();
        if(!accountIds.isEmpty()){
            QueryWrapper<OrganizationManager> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("account_id", accountIds);
            List<OrganizationManager> list = organizationManagerService.list(queryWrapper);
            if(!list.isEmpty()){
                managerMap = list.stream().collect(Collectors.groupingBy(OrganizationManager::getAccountId));
            }
            staffFieldMap.setManagerMap(managerMap);
        }
    }
    /**
     * 权限组中的角色与项目权限
     */
    private void permissionHandler(Map<Integer,List<PermissionGroup>> permissionInfo,StaffFieldMap staffFieldMap){
        Map<Integer, List<PermissionGroupDTO>> map = new HashMap<>();
        List<PermissionGroupDTO> groupDTOS = new ArrayList<>();
        Set<Integer> projectId = new HashSet();
        Set<Integer> roleId = new HashSet();
        for (List<PermissionGroup> value : permissionInfo.values()) {
            for (PermissionGroup permissionGroup : value) {
                if(StringUtils.isNotEmpty(permissionGroup.getProjectIds())){
                    List<Integer> projectIds = Arrays.asList(permissionGroup.getProjectIds().split(",")).stream().map(Integer::valueOf).collect(Collectors.toList());
                    projectId.addAll(projectIds);
                }
                if(StringUtils.isNotEmpty(permissionGroup.getRoleIds())){
                    List<Integer> roleIds = Arrays.asList(permissionGroup.getRoleIds().split(",")).stream().map(Integer::valueOf).collect(Collectors.toList());
                    roleId.addAll(roleIds);
                }
            }
        }
        List<Project> projects = new ArrayList<>();
        if(!CollectionUtils.isEmpty(projectId)){
            projects = projectService.listByIds(projectId);
        }
        List<Role> roles = new ArrayList<>();
        if(!CollectionUtils.isEmpty(roleId)){
            roles = roleService.listByIds(roleId);
        }
        for (List<PermissionGroup> value : permissionInfo.values()){
            for (int j = 0; j < value.size(); j ++){
                PermissionGroupDTO groupDTO = new PermissionGroupDTO();
                if (StringUtils.isEmpty(value.get(j).getRoleIds())){
                    continue;
                }
                List<Integer> roleIds = Arrays.asList(value.get(j).getRoleIds().split(",")).stream().map(Integer::valueOf).collect(Collectors.toList());
                if (StringUtils.isNotEmpty(value.get(j).getProjectIds())){
                    List<Integer> projectIds = Arrays.asList(value.get(j).getProjectIds().split(",")).stream().map(Integer::valueOf).collect(Collectors.toList());
                    List<String> projectNames = projects.stream().filter(i -> projectIds.contains(i.getId())).map(k -> k.getName()).collect(Collectors.toList());
                    groupDTO.setProjectNames(projectNames);
                }
                List<String> roleNames = roles.stream().filter(k -> roleIds.contains(k.getId())).map(i -> i.getName()).collect(Collectors.toList());

                BeanUtils.copyProperties(value.get(j), groupDTO);
                groupDTO.setRoleNames(roleNames);
                groupDTOS.add(groupDTO);
            }
        }
        if (CollectionUtils.isNotEmpty(groupDTOS)){
            map = groupDTOS.stream().collect(Collectors.groupingBy(PermissionGroupDTO ::getAccountId));
        }
        staffFieldMap.setPermissionMap(map);
    }

    /**
     * 业务类型字段信息
     * @param staffIds
     */
    private void staffBusinessTypeHandler(List<StaffDTO> records, List<Integer> staffIds){
        // 业务类型
        QueryWrapper<StaffBusinessRelation> staffBusinessRelationQueryWrappe = new QueryWrapper<>();
        staffBusinessRelationQueryWrappe.select("staff_id", "business_id");
        staffBusinessRelationQueryWrappe.in("staff_id", staffIds);
        List<StaffBusinessRelation> list2 = staffBusinessRelationService.list(staffBusinessRelationQueryWrappe);
        List<Integer> collect1 = list2.stream().map(i -> i.getBusinessId()).distinct().collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(collect1)){
            Map<Integer, String> businessTypeMap = staffBusinessTypeService.listByIds(collect1).stream().collect(Collectors.toMap(StaffBusinessType::getId, StaffBusinessType::getName));
            if(CollectionUtils.isNotEmpty(list2)){
                Map<Integer, List<StaffBusinessRelation>> staffBusinessMap = list2.stream().collect(Collectors.groupingBy(StaffBusinessRelation::getStaffId));
                for (StaffDTO record : records) {
                    List<StaffBusinessRelation> staffBusinessRelations = staffBusinessMap.get(record.getId());
                    if(CollectionUtils.isNotEmpty(staffBusinessRelations)){
                        List<Integer> collect = staffBusinessRelations.stream().map(i -> i.getBusinessId()).collect(Collectors.toList());
                        record.setBusinessIds(collect);
                        record.setBusinessNames(collect.stream().map(i -> businessTypeMap.get(i)).collect(Collectors.toList()));
                    }
                }
            }
        }
    }

    /**
     * 空间数据
     * @param accountIds
     * @param staffFieldMap
     */
    private void spaceViewHandler(List<Integer> accountIds, StaffFieldMap staffFieldMap){
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.in("account_id", accountIds);
        accountOrganizationQueryWrapper.in("type", organizationTypeService.spaceIds());
        List<AccountOrganization> list = accountOrganizationService.list(accountOrganizationQueryWrapper);
        List<Integer> orgIds = list.stream().map(i -> i.getOrganizationId()).distinct().collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(orgIds)){
            Map<Integer, Organization> organizationMap = organizationService.listByIds(orgIds).stream().collect(Collectors.toMap(Organization::getId, Function.identity()));
            Map<Integer, List<AccountOrganization>> accountOrganizationMap = list.stream().collect(Collectors.groupingBy(AccountOrganization::getAccountId));
            Map<Integer, List<Organization>> spaceMap = new HashMap<>();
            for (Map.Entry<Integer, List<AccountOrganization>> integerListEntry : accountOrganizationMap.entrySet()) {
                List<Organization> collect = integerListEntry.getValue().stream().map(i -> organizationMap.get(i.getOrganizationId())).collect(Collectors.toList());
                spaceMap.put(integerListEntry.getKey(), collect);
            }
            staffFieldMap.setSpaceMap(spaceMap);
        }
    }

    /**
     * 岗位
     * @param positionIds
     * @param staffFieldMap
     */
    private void positionHandler(List<Integer> positionIds, StaffFieldMap staffFieldMap){
        Map<Integer, String> positionMap = new HashMap<>();
        if(!positionIds.isEmpty()){
            QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
            positionQueryWrapper.select("id", "name");
            positionQueryWrapper.in("id", positionIds);
            List<Position> list = positionService.list(positionQueryWrapper);
            if(!list.isEmpty()){
                positionMap = list.stream().collect(Collectors.toMap(Position::getId, Position::getName));
            }
            staffFieldMap.setPositionMap(positionMap);
        }
    }

    /**
     * 扩展信息
     * @param staffIds
     * @param staffFieldMap
     */
    private void extraInfoHandler(List<Integer> staffIds, StaffFieldMap staffFieldMap){
        QueryWrapper<StaffExtra> staffExtraQueryWrapper = new QueryWrapper<>();
        staffExtraQueryWrapper.in("staff_id", staffIds);
        List<StaffExtra> list1 = staffExtraService.list(staffExtraQueryWrapper);
        Map<Integer, StaffExtra> extraMap = new HashMap<>();
        if(!list1.isEmpty()){
            extraMap = list1.stream().collect(Collectors.toMap(StaffExtra::getStaffId, Function.identity(), (key1, key2) -> key1));
            staffFieldMap.setExtraMap(extraMap);
        }
    }

    @Override
    public Page<StaffDTO> pageWithOrgIds(StaffQuery staffQuery, Page page) {
        // 查询下级组织
        if (!staffQuery.isShowCurrent()) {
            getChildOrg(staffQuery);
        }
        long cu = System.currentTimeMillis();
        Page<StaffDTO> page1 = staffDao.page(page, staffQuery);
        List<StaffDTO> records = page1.getRecords();
        if(!CollectionUtils.isEmpty(records)) {
            List<Integer> staffIds = records.stream().map(i -> i.getId()).collect(Collectors.toList());
            Map<Integer, List<Organization>> deptInfo = findDeptAllEntityMap(staffIds);
            for (StaffDTO record : records) {
                List<Organization> organizations = deptInfo.get(record.getId());
                if (!CollectionUtils.isEmpty(organizations)) {
                    organizations.removeAll(Collections.singletonList(null));
                    if (!CollectionUtils.isEmpty(organizations)) {
                        record.setOrgIds(organizations.stream().map(i -> i.getId()).collect(Collectors.toList()));
                    }
                }
            }
        }
        log.info("spend {}", (System.currentTimeMillis() - cu));
        long l = System.currentTimeMillis();
        accountInfoSetter(page1.getRecords());
        log.info("spend 2 {}", (System.currentTimeMillis() - l));
        return page1;
    }

    /**
     * 补充帐号信息
     * @param records
     */
    private void accountInfoSetter(List<StaffDTO> records){
        // 补充帐号信息
        if(!CollectionUtils.isEmpty(records)){
            List<Integer> collect = records.stream().map(i -> i.getAccountId()).collect(Collectors.toList());
            List<Account> accounts = accountService.listByIds(collect);
            if(!CollectionUtils.isEmpty(accounts)){
                Map<Integer, Account> accountMap = accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
                for (StaffDTO record : records) {
                    Account account = accountMap.get(record.getAccountId());
                    if(null != account){
                        record.setLoginName(account.getLoginName());
                        record.setName(account.getName());
                        record.setPhone(account.getPhone());
                        record.setSex(account.getSex());
                        record.setFaceUrl(account.getFaceUrl());
                        record.setFaceId(account.getFaceId());
                        record.setEmail(account.getEmail());
                        record.setIdCard(account.getIdCard());
                    }
                }
            }
        }
    }

    /**
     * 查询下级
     *
     * @param staffQuery
     */
    private void getChildOrg(StaffQuery staffQuery) {
        List<Integer> orgId = new ArrayList<>();
        if (null != staffQuery.getOrgId() || null != staffQuery.getOrgIds()) {
            OrganizationQuery organizationQuery = new OrganizationQuery();
            organizationQuery.withId(staffQuery.getOrgId());
            organizationQuery.withIds(staffQuery.getOrgIds());
            organizationQuery.withTypes(Arrays.asList(OrganizationTypeEnum.ORG.id.intValue(), OrganizationTypeEnum.PROJECT.id.intValue()));
            List<Organization> child = organizationService.child(organizationQuery);
            if (!child.isEmpty()) {
                orgId.addAll(child.stream().map(i -> i.getId()).collect(Collectors.toList()));
            }
        }
        if (null != staffQuery.getEnterpriseId()) {
            Enterprise ent = enterpriseService.findById(staffQuery.getEnterpriseId());
            if (null != ent) {
                OrganizationQuery organizationQuery = new OrganizationQuery();
                organizationQuery.withId(ent.getOrganizationId());
                organizationQuery.withTypes(Arrays.asList(OrganizationTypeEnum.ORG.id.intValue(), OrganizationTypeEnum.PROJECT.id.intValue()));
                List<Organization> child = organizationService.child(organizationQuery);
                if (!child.isEmpty()) {
                    orgId.addAll(child.stream().map(i -> i.getId()).collect(Collectors.toList()));
                }
            }
        }
        if (CollectionUtils.isNotEmpty(orgId)) {
            List<Integer> collect = orgId.stream().distinct().collect(Collectors.toList());
            staffQuery.setOrgIds(collect);
        }
    }

    @Override
    public StaffDTO deleteDetail(Integer id) {
        StaffDTO staffDTO = new StaffDTO();
        AccountDeleteLog accountDeleteLog = accountDeleteLogService.getBaseMapper().selectById(id);
        if (null == accountDeleteLog) {
            throw new BusinessException("离职人员数据不存在");
        }
        List<Staff> staffList = staffDao.deleteDetail(accountDeleteLog.getAccountId());
        Staff detail = staffList.get(0);
        if (null == detail) {
            throw new BusinessException("离职员工不存在");
        }
        Account account = accountService.findById(detail.getAccountId());
        if (null == account) {
            throw new DataException("帐号不存在");
        }
        BeanUtils.copyProperties(detail, staffDTO);
        BeanUtils.copyProperties(account, staffDTO);
        staffDTO.setId(detail.getId());
        staffDTO.setIndustryId(account.getIndustryId());
        account.setPassword(null);
        // 业务类型
        getBusinessType(staffDTO);
        if (null != staffDTO.getPositionId()) {
            Position p = positionService.getById(staffDTO.getPositionId());
            staffDTO.setPositionName(p.getName());
        }
        if (staffDTO.getStaffState() != null) {
            staffDTO.setStaffStateName(StaffStateEnum.idOf(staffDTO.getStaffState()));
        }
        if (staffDTO.getStaffType() != null) {
            staffDTO.setStaffTypeName(StaffTypeEnum.idOf(staffDTO.getStaffType()));
        }
        if (null != staffDTO.getNation()) {
            staffDTO.setNationId(staffDTO.getNation().code);
        }
        if (null != staffDTO.getCardType()) {
            staffDTO.setCardTypeName(staffDTO.getCardType().description);
        }
        // 从人脸库获取人脸图片地址
        QueryFaceDTO queryFaceDTO = new QueryFaceDTO();
        queryFaceDTO.setAccountId(account.getId());
        try {
            List<QueryFaceVO> faceVOS = faceManageService.queryFace(queryFaceDTO);
            if (CollectionUtils.isNotEmpty(faceVOS)) {
                int size = faceVOS.size() - 1;
                staffDTO.setFaceUrl(faceVOS.get(size).getFaceUrl());
            }
        } catch (Exception e) {
            log.error("调用人脸失败  {}", e.getMessage());
        }
        QueryWrapper<StaffExtra> staffExtraQueryWrapper = new QueryWrapper<>();
        staffExtraQueryWrapper.eq("staff_id", staffDTO.getId());
        StaffExtra staffExtra = staffExtraDao.selectOne(staffExtraQueryWrapper);
        if (null != staffExtra) {
            staffDTO.setStaffExtra(staffExtra);
        }
        if (null != staffDTO.getPoliticsStatus()) {
            staffDTO.setPoliticsStatusId(staffDTO.getPoliticsStatus().code);
            staffDTO.setPoliticsStatusName(staffDTO.getPoliticsStatus().name);
        }
        if (null != staffDTO.getNation()) {
            staffDTO.setNationId(staffDTO.getNation().getCode());
            staffDTO.setNationName(staffDTO.getNation().name);
        }
        if (null != staffDTO.getEducationalLevel()) {
            staffDTO.setEducationalLevelId(staffDTO.getEducationalLevel().code);
            staffDTO.setEducationalLevelName(staffDTO.getEducationalLevel().name);
        }
        if (CollectionUtils.isNotEmpty(staffDTO.getBusinessIds())) {
            List<StaffBusinessType> staffBusinessTypes = businessTypeDao.selectBatchIds(staffDTO.getBusinessIds());
            if (CollectionUtils.isNotEmpty(staffBusinessTypes)) {
                staffDTO.setBusinessNames(staffBusinessTypes.stream().map(i -> i.getName()).collect(Collectors.toList()));
            }
        }
        if (null != staffDTO.getHigherUp()) {
            Account acc = accountService.findById(staffDTO.getHigherUp());
            staffDTO.setHigherUpName(acc.getName());
        }
        staffDTO.setPassword(null);
        return staffDTO;
    }

    @Override
    public StaffDTO detail(Integer id, Integer enterpriseId, Integer accountId, Integer industryId) {
        StaffDTO staffDTO = new StaffDTO();
        // 帐号 或者 员工id和企业id  必须满足一个
        if(null == id){
            QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
            staffOrganizationQueryWrapper.eq("enterprise_id", enterpriseId);
            staffOrganizationQueryWrapper.eq("account_id", accountId);
            List<StaffOrganization> staffOrganizations = staffOrganizationDao.selectList(staffOrganizationQueryWrapper);
            if(staffOrganizations.isEmpty()){
                throw new DataException("员工不存在 accountId:" +  accountId +" enterpriseId : " + enterpriseId);
            }
            id = staffOrganizations.get(0).getStaffId();
        }
        // 不能用帐号id查询 会查出多个
        Staff detail = staffDao.detail(id, null);
        if (null == detail) {
            throw new DataException("员工不存在");
        }
        Account account = accountService.findById(detail.getAccountId());
        if (null == account) {
            throw new DataException("帐号不存在");
        }
        BeanUtils.copyProperties(detail, staffDTO);
        BeanUtils.copyProperties(account, staffDTO);
        staffDTO.setId(detail.getId());
        staffDTO.setIndustryId(account.getIndustryId());
        getProject(detail.getAccountId(), enterpriseId, staffDTO);
        // 员工关联的企业项目空间信息放在这里
        getOrganizationInfo(detail.getId(), enterpriseId, staffDTO);
        getRole(detail.getAccountId(), enterpriseId, staffDTO);
        // 业务类型
        getBusinessType(staffDTO);
        if (null != staffDTO.getPositionId()) {
            Position p = positionService.getById(staffDTO.getPositionId());
            staffDTO.setPositionName(p.getName());
        }
        if (staffDTO.getStaffState() != null) {
            staffDTO.setStaffStateName(StaffStateEnum.idOf(staffDTO.getStaffState()));
        }
        if (staffDTO.getStaffType() != null) {
            staffDTO.setStaffTypeName(StaffTypeEnum.idOf(staffDTO.getStaffType()));
        }
        if (null != staffDTO.getNation()) {
            staffDTO.setNationId(staffDTO.getNation().code);
        }
        if (null != staffDTO.getCardType()) {
            staffDTO.setCardTypeName(staffDTO.getCardType().description);
        }
        if (null != staffDTO.getWorkingTime()) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            staffDTO.setWorkingTimeShow(simpleDateFormat.format(staffDTO.getWorkingTime()));
        }
        // 从人脸库获取人脸图片地址
        QueryFaceDTO queryFaceDTO = new QueryFaceDTO();
        queryFaceDTO.setAccountId(account.getId());
        try {
            List<QueryFaceVO> faceVOS = faceManageService.queryFace(queryFaceDTO);
            if (CollectionUtils.isNotEmpty(faceVOS)) {
                int size = faceVOS.size() - 1;
                staffDTO.setFaceUrl(faceVOS.get(size).getFaceUrl());
            }
        } catch (Exception e) {
            log.error("调用人脸失败  {}", e.getMessage());
        }
        //封装员工证书附件信息
        QueryWrapper<StaffCertificate> staffCertificateQueryWrapper = new QueryWrapper<>();
        staffCertificateQueryWrapper.eq("staff_id",id);
        List<StaffCertificate> staffCertificateQueryList = staffCertificateService.list(staffCertificateQueryWrapper);
        if (null != staffCertificateQueryList){
            staffDTO.setCertificate(staffCertificateQueryList);
        }
        QueryWrapper<StaffExtra> staffExtraQueryWrapper = new QueryWrapper<>();
        staffExtraQueryWrapper.eq("staff_id", staffDTO.getId());
        StaffExtra staffExtra = staffExtraDao.selectOne(staffExtraQueryWrapper);
        if (null != staffExtra) {
            staffDTO.setStaffExtra(staffExtra);
        }
        if (null != staffDTO.getPoliticsStatus()) {
            staffDTO.setPoliticsStatusId(staffDTO.getPoliticsStatus().code);
            staffDTO.setPoliticsStatusName(staffDTO.getPoliticsStatus().name);
        }
        if (null != staffDTO.getNation()) {
            staffDTO.setNationId(staffDTO.getNation().getCode());
            staffDTO.setNationName(staffDTO.getNation().name);
        }
        if (null != staffDTO.getEducationalLevel()) {
            staffDTO.setEducationalLevelId(staffDTO.getEducationalLevel().code);
            staffDTO.setEducationalLevelName(staffDTO.getEducationalLevel().name);
        }
        if (CollectionUtils.isNotEmpty(staffDTO.getBusinessIds())) {
            List<StaffBusinessType> staffBusinessTypes = businessTypeDao.selectBatchIds(staffDTO.getBusinessIds());
            if (CollectionUtils.isNotEmpty(staffBusinessTypes)) {
                staffDTO.setBusinessNames(staffBusinessTypes.stream().map(i -> i.getName()).collect(Collectors.toList()));
            }
        }
        if (null != staffDTO.getHigherUp()) {
            Account acc = accountService.findById(staffDTO.getHigherUp());
            staffDTO.setHigherUpName(acc.getName());
        }
        staffDTO.setPassword(null);
        getPermissionGroup(staffDTO, enterpriseId, industryId);
        return staffDTO;
    }

    /**
     * 获取当前帐号的权限组
     * @param staffDTO
     */
    private void getPermissionGroup(StaffDTO staffDTO, Integer enterpriseId, Integer industryId){
        QueryWrapper<PermissionGroup> permissionGroupQueryWrapper = new QueryWrapper<>();
        permissionGroupQueryWrapper.eq("account_id", staffDTO.getAccountId());
        permissionGroupQueryWrapper.eq("enterprise_id", enterpriseId);
        permissionGroupQueryWrapper.orderByAsc("created_at");
        List<PermissionGroup> list = permissionGroupService.list(permissionGroupQueryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            List<PermissionGroupDTO> permissionGroups = new ArrayList<>(list.size());
            List<Integer> projectIds = new ArrayList<>();
            List<Integer> roleIds = new ArrayList<>();
            for (PermissionGroup permissionGroup : list) {
                PermissionGroupDTO permissionGroupDTO = new PermissionGroupDTO();
                BeanUtils.copyProperties(permissionGroup, permissionGroupDTO);
                if (StringUtils.isNotEmpty(permissionGroup.getProjectIds())) {
                    List<Integer> collect = Arrays.asList(permissionGroup.getProjectIds().split(",")).stream().map(i -> Integer.valueOf(i)).collect(Collectors.toList());
                    projectIds.addAll(collect);
                    permissionGroupDTO.setProjectList(collect);
                }
                if (StringUtils.isNotEmpty(permissionGroup.getRoleIds())) {
                    List<Integer> collect2 = Arrays.asList(permissionGroup.getRoleIds().split(",")).stream().map(i -> Integer.valueOf(i)).collect(Collectors.toList());
                    roleIds.addAll(collect2);
                    permissionGroupDTO.setRoleList(collect2);
                }
                permissionGroups.add(permissionGroupDTO);
            }
            List<Project> projects = null;
            if (!projectIds.isEmpty()) {
                QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
                projectQueryWrapper.select("id", "name");
                projectQueryWrapper.in("id", projectIds.stream().distinct().collect(Collectors.toList()));
                projects = projectDao.selectList(projectQueryWrapper);
            }

            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.select("id", "industry_id", "name", "grade", "type", "enterprise_id");
            roleQueryWrapper.in("id", roleIds.stream().distinct().collect(Collectors.toList()));
            List<Role> roles = roleService.list(roleQueryWrapper);
            List<PermissionGroupDTO> resultGroup = new ArrayList<>();
            for (PermissionGroupDTO permissionGroup : permissionGroups) {
                List<Integer> roleIds1 = permissionGroup.getRoleList();
                List<Role> collect = roles.stream().filter(i -> roleIds1.contains(i.getId())).collect(Collectors.toList());
                // 如果不包含业态角色 又不包含当前企业角色的权限组就不展示
                if(null ==  enterpriseId || null == industryId){
                    log.info("当前权限组 {} 入参为空不满足在平台 {}, 企业 {} 下的展示要求", permissionGroup.getId(), industryId, enterpriseId);
                    continue;
                }
                if(containOtherIndustryRole(collect, industryId)){
                    log.info("当前权限组 {} 包含了其他业态角色不满足在平台 {}, 企业 {} 下的展示要求", permissionGroup.getId(), industryId, enterpriseId);
                    continue;
                }
                // 业态角色
                List<Role> collect2 = collect.stream().filter(i -> i.getGrade().intValue() == 2 ).collect(Collectors.toList());
                // 企业角色
                List<Role> collect3 = collect.stream().filter(i -> i.getGrade().intValue() == 1 ).collect(Collectors.toList());
                // 如果业态角色不为空则必须展示该权限组
                if(collect2.isEmpty()){
                    if(collect2.isEmpty() && collect3.isEmpty()){
                        log.info("当前权限组 {} 不满足在平台 {}, 企业 {} 下的展示要求", permissionGroup.getId(), industryId, enterpriseId);
                        continue;
                    }
                    List<Integer> enterpriseIds = collect3.stream().map(i -> i.getEnterpriseId()).collect(Collectors.toList());
                    if(!enterpriseIds.contains(enterpriseId)){
                        log.info("当前权限组 {} 不满足在平台 {}, 企业 {} 下的展示要求", permissionGroup.getId(), industryId, enterpriseId);
                        continue;
                    }
                }
                // 回填权限组的项目, 角色名称
                List<Integer> projectIds1 = permissionGroup.getProjectList();
                if (CollectionUtils.isNotEmpty(projects) && CollectionUtils.isNotEmpty(projectIds1)) {
                    List<String> collect1 = projects.stream().filter(i -> projectIds1.contains(i.getId())).map(j -> j.getName()).collect(Collectors.toList());
                    permissionGroup.setProjectNames(collect1);
                }
                List<Integer> roleIds4 = permissionGroup.getRoleList();
                List<String> roleNames = new ArrayList<>();
                Map<Integer,String> roleNameMap = roles.stream().distinct().collect(Collectors.toMap(Role::getId,Role::getName));
                for (Integer integer :roleIds4){
                    roleNames.add(roleNameMap.get(integer));
                }
                permissionGroup.setRoleNames(roleNames);
                resultGroup.add(permissionGroup);
            }
            staffDTO.setPermissionGroupDTOs(resultGroup);
        }
    }

    /**
     * 判断是否包含其他业态的角色
     * @param collect
     * @param industryId
     * @return
     */
    private boolean containOtherIndustryRole(List<Role> collect, Integer industryId){
        for (Role role : collect) {
            // 业态角色不属于当前业态的时候不展示
            if(role.getGrade() == 2 && !(role.getIndustryId().intValue() == industryId)){
                return true;
            }
        }
        return false;
    }

    private void getBusinessType(StaffDTO staffDTO) {
        Integer id = staffDTO.getId();
        QueryWrapper<StaffBusinessRelation> staffBusinessRelationQueryWrapper = new QueryWrapper<>();
        staffBusinessRelationQueryWrapper.eq("staff_id", id);
        List<StaffBusinessRelation> list = staffBusinessRelationService.list(staffBusinessRelationQueryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Integer> collect = list.stream().map(i -> i.getBusinessId()).collect(Collectors.toList());
            QueryWrapper<StaffBusinessType> staffBusinessTypeQueryWrapper = new QueryWrapper<>();
            staffBusinessTypeQueryWrapper.select("id", "name");
            List<StaffBusinessType> staffBusinessTypes = businessTypeDao.selectList(staffBusinessTypeQueryWrapper);
            staffDTO.setBusinessIds(collect);
            if (CollectionUtils.isNotEmpty(staffBusinessTypes)) {
                staffDTO.setBusinessNames(staffBusinessTypes.stream().map(i -> i.getName()).collect(Collectors.toList()));
            }
        }
    }

    @Override
    public ResultJson bind(StaffDTO staffDTO, Account operator) {
        ResultJson resultJson1 = staffCheck(staffDTO, operator, true);
        if (!resultJson1.getState()) {
            return resultJson1;
        }
        Staff staff = new Staff();
        BeanUtils.copyProperties(staffDTO, staff);
        // 根据手机号查询关联的帐号
        Account account = accountService.phoneExistV2(staffDTO.getPhone(), operator.getDevelopId());
        if (null == account) {
            return ResultJson.fail("帐号不存在");
        }
        // 判断是否已经存在员工信息
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.eq("account_id", account.getId());
        staffOrganizationQueryWrapper.eq("enterprise_id", staffDTO.getEnterpriseId().get(0));
        List<StaffOrganization> staff1 = staffOrganizationDao.selectList(staffOrganizationQueryWrapper);
        if (staff1.size() > 0) {
            return resultJson1.fail("员工信息已存在");
        }
        //校验是否重复绑定
        QueryWrapper<StaffOrganization> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("account_id", account.getId());
        queryWrapper.eq("enterprise_id", staffDTO.getEnterpriseId().get(0));
        List<StaffOrganization> list = staffOrganizationService.list(queryWrapper);
        // 已经绑定过了
        if(CollectionUtils.isNotEmpty(list)){
            return ResultJson.fail("帐号已存在，不可以重复添加");
        }
        // 执行绑定操作
        // 保存员工信息
        staff.setAccountId(account.getId());
        staff.setName(account.getName());
        staffDao.insert(staff);
        // 保存组织信息 staffOrganization
        saveOrganization(staffDTO, account, staff);
        permissionConnect(account.getId(), staffDTO.getProjectIds(), staffDTO.getRoleIds());
        // 绑定权限组
        permissionGroupConnect(account.getId(), staffDTO.getPermissionGroupDTOs());
        return ResultJson.success();
    }

    /**
     * 新增权限组信息
     * @param id
     * @param permissionGroupDTOs
     */
    private void permissionGroupConnect(Integer id, List<PermissionGroupDTO> permissionGroupDTOs) {
        List<PermissionGroup> permissionGroups = new ArrayList<>(permissionGroupDTOs.size());
        Integer enyId = permissionGroupDTOs.get(0).getEnterpriseId();
        for (PermissionGroupDTO permissionGroupDTO : permissionGroupDTOs) {
            PermissionGroup permissionGroup = new PermissionGroup();
            List<Integer> roleIds = permissionGroupDTO.getRoleList();
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(roleIds)) {
                throw new BusinessException("缺少角色信息");
            }
            roleIds = roleIds.stream().distinct().collect(Collectors.toList());
            permissionGroup.setRoleIds(Joiner.on(",").join(roleIds));
            List<Integer> projectIds = permissionGroupDTO.getProjectList();
            if (!org.apache.commons.collections4.CollectionUtils.isEmpty(projectIds)) {
                projectIds = projectIds.stream().distinct().collect(Collectors.toList());
                permissionGroup.setProjectIds(Joiner.on(",").join(projectIds));
            }
            //填充企业id
            if (null != enyId){
                permissionGroup.setEnterpriseId(enyId);
            }
            permissionGroup.setAccountId(id);
            permissionGroups.add(permissionGroup);
        }
        permissionGroupService.saveBatch(permissionGroups);

    }

    @Override
    @Transactional
    public void removeProject(Integer staffId, Integer projectId) {
        Staff staff = staffDao.selectById(staffId);
        if (null == staff) {
            throw new DataException("员工不存在");
        }
        Account account = accountService.findById(staff.getAccountId());
        if (null == account) {
            throw new DataException("帐号不存在");
        }
        Project project = projectService.findById(projectId);
        if (null == project) {
            throw new DataException("项目不存在");
        }
        // 帐号和项目关联
        QueryWrapper<AccountProject> accountProjectQueryWrapper = new QueryWrapper<>();
        accountProjectQueryWrapper.eq("project_id", projectId);
        accountProjectQueryWrapper.eq("account_id", account.getId());
        accountProjectService.remove(accountProjectQueryWrapper);
        // 帐号和组织关联
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("account_id", account.getId());
        accountOrganizationQueryWrapper.eq("orgnaization_id", project.getOrganizationId());
        accountOrganizationService.remove(accountOrganizationQueryWrapper);
        // 员工和组织关联
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.eq("staff_id", staffId);
        staffOrganizationQueryWrapper.eq("org_id", project.getOrganizationId());
        staffOrganizationService.remove(staffOrganizationQueryWrapper);
    }

    @Override
    public Map<Integer, List<String>> findProjectMap(List<Integer> staffIds) {
        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        staffQueryWrapper.select("id", "account_id");
        staffQueryWrapper.eq("is_deleted", false);
        staffQueryWrapper.in("id", staffIds);
        List<Staff> staff = staffDao.selectList(staffQueryWrapper);
        if (staff.isEmpty()) {
            log.warn("员工信息不存在");
            return Collections.emptyMap();
        }
        List<Integer> accountId = staff.stream().map(i -> i.getAccountId()).collect(Collectors.toList());
        QueryWrapper<AccountProject> accountProjectQueryWrapper = new QueryWrapper<>();
        accountProjectQueryWrapper.in("account_id", accountId);
        List<AccountProject> accountProjects = accountProjectService.list(accountProjectQueryWrapper);
        if (accountProjects.isEmpty()) {
            log.warn("帐号暂未关联项目信息");
            return Collections.emptyMap();
        }
        List<Integer> projectIds = accountProjects.stream().map(i -> i.getProjectId()).distinct().collect(Collectors.toList());
        Map<Integer, List<Integer>> accountProjectMap = accountProjects.stream().filter(i -> null != i.getProjectId()).collect(Collectors.groupingBy(AccountProject::getAccountId, Collectors.mapping(AccountProject::getProjectId, Collectors.toList())));
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.setIds(projectIds);
        List<Project> project = projectService.list(projectQuery, null);
        if (project.isEmpty()) {
            log.warn("项目信息不存在");
            return Collections.emptyMap();
        }
        Map<Integer, String> projectNameMap = project.stream().collect(Collectors.toMap(Project::getId, Project::getName));
        Map<Integer, List<String>> result = new HashMap<>(accountProjectMap.size());
        for (Map.Entry<Integer, List<Integer>> integerListEntry : accountProjectMap.entrySet()) {
            List<Integer> value = integerListEntry.getValue();
            List<String> projectNames = value.stream().map(i -> projectNameMap.get(i)).collect(Collectors.toList());
            result.put(integerListEntry.getKey(), projectNames);
        }
        return result;
    }
    

    @Override
    public ResultJson findProjectMap1(List<Integer> staffIds) {
        return ResultJson.success(findProjectMap(staffIds));
    }

    @Override
    public Map<Integer, List<String>> findRoleMap(List<Integer> accountIds) {
        return accountService.getAccountRoles(accountIds);
    }

    @Override
    public Map<Integer, List<String>> findDeptMap(List<Integer> staffIds) {
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.in("staff_id", staffIds);
        List<StaffOrganization> staffOrganizations = staffOrganizationService.list(staffOrganizationQueryWrapper);
        List<Integer> orgIds = staffOrganizations.stream().map(i -> i.getOrgId()).distinct().collect(Collectors.toList());
        Map<Integer, List<Integer>> staffOrgIdsMap = staffOrganizations.stream().collect((Collectors.groupingBy(StaffOrganization::getStaffId, Collectors.mapping(StaffOrganization::getOrgId, Collectors.toList()))));
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.withIds(orgIds);
        List<Organization> organizations = organizationService.list(organizationQuery);
        if (organizations.isEmpty()) {
            log.warn("数据错误，查询不到组织信息");
            return Collections.emptyMap();
        }
        Map<Integer, String> orgNameMap = organizations.stream().collect(Collectors.toMap(Organization::getId, Organization::getName));
        Map<Integer, List<String>> result = new HashMap<>(staffOrgIdsMap.size());
        for (Map.Entry<Integer, List<Integer>> integerListEntry : staffOrgIdsMap.entrySet()) {
            List<String> names = integerListEntry.getValue().stream().map(i -> orgNameMap.get(i)).collect(Collectors.toList());
            result.put(integerListEntry.getKey(), names);
        }
        return result;
    }

    @Override
    public Map<Integer, List<Organization>> findDeptAllEntityMap(List<Integer> staffIds) {
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.in("staff_id", staffIds);
        List<StaffOrganization> staffOrganizations = staffOrganizationService.list(staffOrganizationQueryWrapper);
        List<Integer> orgIds = staffOrganizations.stream().map(i -> i.getOrgId()).distinct().collect(Collectors.toList());
        Map<Integer, List<Integer>> staffOrgIdsMap = staffOrganizations.stream().collect((Collectors.groupingBy(StaffOrganization::getStaffId, Collectors.mapping(StaffOrganization::getOrgId, Collectors.toList()))));
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.withIds(orgIds);
        List<Organization> organizations = organizationService.list(organizationQuery);
        if (organizations.isEmpty()) {
            log.warn("数据错误，查询不到组织信息");
            return Collections.emptyMap();
        }
        Map<Integer, Organization> orgNameMap = organizations.stream().collect(Collectors.toMap(Organization::getId, Function.identity()));
        Map<Integer, List<Organization>> result = new HashMap<>(staffOrgIdsMap.size());
        for (Map.Entry<Integer, List<Integer>> integerListEntry : staffOrgIdsMap.entrySet()) {
            List<Organization> names = integerListEntry.getValue().stream().map(i -> orgNameMap.get(i)).collect(Collectors.toList());
            result.put(integerListEntry.getKey(), names);
        }
        return result;
    }

    @Override
    public ResultJson findDeptAllEntityMap1(List<Integer> staffIds) {
        return ResultJson.success(findDeptAllEntityMap(staffIds));
    }

    @Override
    public Map<Integer, List<PermissionGroup>> findPermissionMap(List<Integer> accountIds) {
        QueryWrapper<PermissionGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("account_id", accountIds);
        List<PermissionGroup> permissionGroups = permissionGroupService.list(queryWrapper);
        List<Integer> groupIds = permissionGroups.stream().map(i -> i.getId()).distinct().collect(Collectors.toList());
        Map<Integer, List<PermissionGroup>> groupIdsMap = permissionGroups.stream().collect(Collectors.groupingBy(PermissionGroup::getAccountId));
        return groupIdsMap;
    }

    @Override
    public Map findByEnterpriseIdList(List<Integer> enterpriseIdList) {
        if (enterpriseIdList.isEmpty()){
            return Collections.EMPTY_MAP;
        }
        //获取所有企业的组织
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<AccountOrganization>().in("enterprise_id", enterpriseIdList);
        List<AccountOrganization> accountOrganizationList = accountOrganizationService.list(accountOrganizationQueryWrapper);
        Map<Integer, List<AccountOrganization>> enterpriseOrgs = accountOrganizationList.stream().collect(Collectors.groupingBy(AccountOrganization::getEnterpriseId));
        List<Integer> organizationIdList = accountOrganizationList.stream().map(AccountOrganization::getOrganizationId).distinct().collect(Collectors.toList());
        //获取所有组织的所有员工
        if (organizationIdList.isEmpty()){
            return Collections.EMPTY_MAP;
        }
        QueryWrapper<StaffOrganization> organizationQueryWrapper = new QueryWrapper<StaffOrganization>().in("org_id", organizationIdList);
        List<StaffOrganization> staffOrganizations = staffOrganizationDao.selectList(organizationQueryWrapper);
        if (staffOrganizations.isEmpty()){
            return Collections.EMPTY_MAP;
        }
        //根据根据企业统计员工数
        HashMap<Integer, Integer> enterpriseIdStaffNumber = new HashMap<>();
        enterpriseIdList.forEach(p ->{
            if (!enterpriseOrgs.keySet().contains(p)){
                enterpriseIdStaffNumber.put(p, 0);
                return;
            }
            List<Integer> enterpriseOrg = enterpriseOrgs.get(p).stream().map(AccountOrganization::getOrganizationId).distinct().collect(Collectors.toList());
            List<Integer> totalStaffs = staffOrganizations.stream().filter(l -> enterpriseOrg.contains(l.getOrgId())).map(StaffOrganization::getStaffId).distinct().collect(Collectors.toList());
            enterpriseIdStaffNumber.put(p, totalStaffs.size());
        });
        return enterpriseIdStaffNumber;
    }

    @Override
    public Long findAllBusinessIdStaff() {
        List<StaffBusinessType> typeList = staffBusinessTypeService.list(new QueryWrapper<>());
        if (typeList.isEmpty()){
            return Long.valueOf(-1);
        }
        List<Integer> businessIdList = typeList.stream().map(StaffBusinessType::getId).collect(Collectors.toList());
        QueryWrapper<StaffBusinessRelation> staffBusinessRelationQueryWrapper = new QueryWrapper<StaffBusinessRelation>().in("business_id", businessIdList);
        List<StaffBusinessRelation> staffBusinessRelations = staffBusinessRelationDao.selectList(staffBusinessRelationQueryWrapper);
        long totalStaff = staffBusinessRelations.stream().map(StaffBusinessRelation::getStaffId).distinct().count();
        return totalStaff;
    }

    @Override
    public List findByBusinessIdList(List<Integer> businessIdList, Integer entId) {
        if (entId == null || businessIdList.isEmpty()){
            return Collections.EMPTY_LIST;
        }
        //根据企业id查询得到所有关联组织
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<AccountOrganization>().eq("enterprise_id", entId);
        List<AccountOrganization> accountOrganizationList = accountOrganizationService.list(accountOrganizationQueryWrapper);
        List<Integer> organizationIdList = accountOrganizationList.stream().map(AccountOrganization::getOrganizationId).distinct().collect(Collectors.toList());
        //根据组织查询员工
        if (organizationIdList.isEmpty()){
            return Collections. EMPTY_LIST;
        }
        QueryWrapper<StaffOrganization> organizationQueryWrapper = new QueryWrapper<StaffOrganization>().in("org_id", organizationIdList);
        List<StaffOrganization> staffOrganizations = staffOrganizationDao.selectList(organizationQueryWrapper);
        List<Integer> staffIdList = staffOrganizations.stream().map(StaffOrganization::getStaffId).distinct().collect(Collectors.toList());
        //查询所有业务类型员工
        if (staffIdList.isEmpty()){
            return  Collections.EMPTY_LIST;
        }
        QueryWrapper<StaffBusinessRelation> staffBusinessRelationQueryWrapper = new QueryWrapper<StaffBusinessRelation>().in("staff_id", staffIdList);
        List<StaffBusinessRelation> staffBusinessRelations = staffBusinessRelationDao.selectList(staffBusinessRelationQueryWrapper);
        List<Object> returnList = new ArrayList<>();
        Map<Integer, List<StaffBusinessRelation>> businessStaffsList = staffBusinessRelations.stream().collect(Collectors.groupingBy(StaffBusinessRelation::getBusinessId));
        List<StaffBusinessType> typeList = businessTypeDao.selectList(new QueryWrapper<>());
        Map<Integer, String> idAndNameMap = typeList.stream().distinct().collect(Collectors.toMap(StaffBusinessType::getId, StaffBusinessType::getName, (p1, p2) -> p2));
        //根据业务类型进行分类
        businessIdList.forEach(p ->{
            Map<String, String> businessFilterMap = new HashMap<>();
            String businessTypeName = idAndNameMap.get(p);
            //p类型是否存在
            List<Integer> existP = businessStaffsList.keySet().stream().filter(k -> k.equals(p)).collect(Collectors.toList());
            if (existP.size() > 0){
                int businessStaffNumber = businessStaffsList.get(p).size();
                businessFilterMap.put("businessId", String.valueOf(p));
                businessFilterMap.put("businessName", businessTypeName);
                businessFilterMap.put("staffCount", String.valueOf(businessStaffNumber));
                returnList.add(businessFilterMap);
                return;
            }
            businessFilterMap.put("businessId", String.valueOf(p));
            businessFilterMap.put("businessName", businessTypeName);
            businessFilterMap.put("staffCount", String.valueOf(0));
            returnList.add(businessFilterMap);
        });
        return returnList;
    }

    @Override
    public Map findAllStaffs() {
        Map<String, Object> returnMap = new HashMap<>();
        QueryWrapper<Enterprise> enterpriseListQw = new QueryWrapper<Enterprise>().eq("is_deleted", 0).eq("status", 1);
        List<Enterprise> enterpriseList = enterpriseService.list(enterpriseListQw);
        if (enterpriseList.isEmpty()){
            returnMap.put("totalCountStaff", 0);
            returnMap.put("rankResult", null);
            return returnMap;
        }
        List<Staff> staffList = staffDao.selectList(new QueryWrapper<Staff>().eq("is_deleted", 0));
        int totalCountStaff = staffList.size();
        List<Integer> accountIds = staffList.stream().map(Staff::getAccountId).collect(Collectors.toList());
        List<Integer> enterpriseIds = enterpriseList.stream().distinct().map(Enterprise::getId).collect(Collectors.toList());
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<StaffOrganization>().in("enterprise_id", enterpriseIds);
        List<StaffOrganization> staffOrganizationList = staffOrganizationDao.selectList(staffOrganizationQueryWrapper);
        List<Map<String, Object>> entStaffNumList = new ArrayList<>();
        enterpriseIds.forEach(entId -> {
            Map<String, Object> entStaffNum = new HashMap<>();
            //查找在表中，且未离职的
            long count = staffOrganizationList.stream().filter(p -> p.getEnterpriseId().equals(entId) && accountIds.contains(p.getAccountId())).map(StaffOrganization::getStaffId).distinct().count();
            String name = enterpriseList.stream().filter(q -> q.getId().equals(entId)).collect(Collectors.toList()).get(0).getName();
            entStaffNum.put("entpriseId", entId);
            entStaffNum.put("entpriseName", name);
            entStaffNum.put("countStaff", count);
            entStaffNumList.add(entStaffNum);
        });
        List<Map<String, Object>> ranks = entStaffNumList.stream().sorted(Comparator.comparingLong(map -> (long) map.get("countStaff"))).collect(Collectors.toList());
        Collections.reverse(ranks);
        for (int i = 0; i < ranks.size(); i++) {
            ranks.get(i).put("rank", i + 1);
        }
        returnMap.put("totalCountStaff",totalCountStaff);
        returnMap.put("rankResult", ranks);
        return returnMap;
    }

    @Override
    @Transactional
    public ResultJson delete(Integer industryId, Integer id, Account operator) {
        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
        staffQueryWrapper.eq("id", id);
        staffQueryWrapper.eq("is_deleted", false);
        Staff staff = staffDao.selectOne(staffQueryWrapper);
        if (null == staff) {
            return ResultJson.fail("员工不存在");
        }
        Account acc = accountService.findById(staff.getAccountId());
        if (null == acc) {
            return ResultJson.fail("帐号不存在");
        }
        //离职员工推送信息
        StaffDTO staffDTO = new StaffDTO();
        BeanUtils.copyProperties(staff,staffDTO);

        staff.setDeleted(true);
        staffDao.updateById(staff);
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.eq("staff_id", id);
        List<StaffOrganization> list = staffOrganizationService.list(staffOrganizationQueryWrapper);
        //离职员工推送信息
//        if (null != industryId) {
//            StaffDTO detail = detail(id, list.get(0).getEnterpriseId(), list.get(0).getAccountId(), industryId);
//            BeanUtils.copyProperties(detail, staffDTO);
//            if (detail != null && CollectionUtil.isNotEmpty(detail.getProjectIds())) {
//                //删除关联项目
//                QueryWrapper<AccountProject> accQueryWrapper = new QueryWrapper<>();
//                accQueryWrapper.eq("account_id", staff.getAccountId());
//                accQueryWrapper.in("project_id", detail.getProjectIds());
//                accountProjectService.remove(accQueryWrapper);
//            }
//        }
        removeStaffProject(staff, list.get(0).getEnterpriseId());
        staffOrganizationService.remove(staffOrganizationQueryWrapper);
        // 删除角色权限
        removeStaffRole(staff, list.get(0).getEnterpriseId());
        // 生成离职人员记录
        AccountDeleteLog accountDeleteLog = new AccountDeleteLog();
        if (CollectionUtils.isNotEmpty(list)) {
            List<Integer> collect = list.stream().map(i -> i.getEnterpriseId()).distinct().collect(Collectors.toList());
            List<Integer> orgIds = list.stream().map(i -> i.getOrgId()).distinct().collect(Collectors.toList());
            accountDeleteLog.setEnterpriseId(collect.get(0));
            accountDeleteLog.setOrgIds(StringUtils.join(orgIds, ","));
        }
        accountDeleteLog.setAccountId(staff.getAccountId());
        accountDeleteLog.setName(acc.getName());
        accountDeleteLogService.save(accountDeleteLog);
        // 删除组织管理员
        QueryWrapper<OrganizationManager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", staff.getAccountId());
        organizationManagerService.remove(queryWrapper);
        // 删除组织数据
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("account_id", staff.getAccountId());
        queryWrapper1.eq("enterprise_id", list.get(0).getEnterpriseId());
        accountOrganizationService.remove(queryWrapper1);
        // 推送离职员工消信息
        staffProducer.delete(staffDTO);
        return ResultJson.success();
    }

    private void removeStaffProject(Staff staff, Integer enterpriseId) {
        QueryWrapper<PermissionGroup> permissionGroupQueryWrapper = new QueryWrapper<>();
        permissionGroupQueryWrapper.eq("account_id",staff.getAccountId());
        permissionGroupQueryWrapper.isNotNull("project_ids");
        permissionGroupQueryWrapper.isNotNull("enterprise_id");
        List<PermissionGroup> permissionGroups = permissionGroupService.list(permissionGroupQueryWrapper);
        //需要删除的
        List<Integer> needRemoveId = new ArrayList<>();
        //不要删除的
        List<Integer> notRemove = new ArrayList<>();

        if (null != permissionGroups && !permissionGroups.isEmpty()){
            for (PermissionGroup p : permissionGroups){
                if (null != p.getProjectIds() && StringUtils.isNotEmpty(p.getProjectIds())){
                    List<Integer> projectIds = Arrays.stream(p.getProjectIds().split(",")).map(Integer::valueOf).collect(Collectors.toList());
                    if (p.getEnterpriseId().equals(enterpriseId)){
                        needRemoveId.addAll(projectIds);
                    }else {
                        notRemove.addAll(projectIds);
                    }
                }
            }
        }
        //从需要删除的id中过滤掉不可删除的id
        List<Integer> projects = needRemoveId.stream().filter(i -> !notRemove.contains(i)).collect(Collectors.toList());
        if (null != projects && !projects.isEmpty()){
            QueryWrapper<AccountProject> accQueryWrapper = new QueryWrapper<>();
            accQueryWrapper.eq("account_id", staff.getAccountId());
            accQueryWrapper.in("project_id", projects);
            accountProjectService.remove(accQueryWrapper);
        }
    }

    /**
     * 移除员工在该企业下的角色权限
     * @param staff
     * @param enterpriseId
     */
    private void removeStaffRole(Staff staff, Integer enterpriseId){
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.select("id");
        roleQueryWrapper.eq("enterprise_id", enterpriseId);
        List<Role> list = roleService.list(roleQueryWrapper);
        accountService.removeRole(staff.getAccountId(), list.stream().map(i -> i.getId()).collect(Collectors.toList()));
        //删除当前企业权限组
        QueryWrapper<PermissionGroup> permissionGroupQueryWrapper = new QueryWrapper<>();
        permissionGroupQueryWrapper.eq("account_id",staff.getAccountId());
        permissionGroupQueryWrapper.eq("enterprise_id",enterpriseId);
        permissionGroupService.remove(permissionGroupQueryWrapper);
    }

    @Override
    public List<StaffDTO> list(StaffQuery staffQuery) {
        // 查询下级组织
        if (!staffQuery.isShowCurrent()) {
            getChildOrg(staffQuery);
        }
        /**
         * 查询雇员，要排除所有的游客角色类型
         */
        RoleQuery roleQuery = new RoleQuery();
        roleQuery.setType(RoleTypeEnum.TOURIST.code);
        List<Role> roleList = roleService.getRoleList(null, roleQuery);
        if (!CollectionUtils.isEmpty(roleList)) {
            List<Integer> collect = roleList.stream().map(role -> role.getId()).collect(Collectors.toList());
            List<Integer> excludeRoleIds = staffQuery.getExcludeRoleIds();
            if (excludeRoleIds == null) {
                excludeRoleIds = new ArrayList<>();
            }
            excludeRoleIds.addAll(collect);
            staffQuery.setExcludeRoleIds(excludeRoleIds);
        }
        List<StaffDTO> list = staffDao.list(staffQuery);
        // 补充帐号信息
        accountInfoSetter(list);
        baseDataSetter(staffQuery,list);
        return list;
    }

    @Override
    public ResultJson batchEditOrg(List<Integer> staffIds, List<Integer> orgIds, Integer enterpriseId) {
        if (CollectionUtils.isEmpty(staffIds)) {
            return ResultJson.success();
        }
        if (CollectionUtils.isEmpty(orgIds)) {
            return ResultJson.fail("缺少组织信息");
        }
        if (null == enterpriseId) {
            return ResultJson.fail("缺少企业信息");
        }
        staffIds = staffIds.stream().distinct().collect(Collectors.toList());
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.withIds(orgIds);
        List<Organization> organizations = organizationService.list(organizationQuery);
        if (organizations.isEmpty()) {
            return ResultJson.fail("组织不存在");
        }
        List<Integer> organizationIds = organizations.stream().map(i -> i.getId()).collect(Collectors.toList());
        StaffQuery staffQuery = new StaffQuery();
        staffQuery.setIds(staffIds);
        List<StaffDTO> list = staffDao.list(staffQuery);
        List<Integer> accountIds = list.stream().map(i -> i.getAccountId()).collect(Collectors.toList());
        // 先删除该员工在企业下之前的组织信息
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.eq("enterprise_id", enterpriseId);
        staffOrganizationQueryWrapper.in("staff_id", staffIds);
        List<Integer> orgIds1 = staffOrganizationService.list(staffOrganizationQueryWrapper).stream().distinct().map(i -> i.getOrgId()).collect(Collectors.toList());
        staffOrganizationService.remove(staffOrganizationQueryWrapper);
        orgIds1.removeAll(organizationIds);
        if (CollectionUtils.isNotEmpty(orgIds1)) {
            //是否是之前组织负责人，是则移除身份
            QueryWrapper<OrganizationManager> organizationManagerQueryWrapper = new QueryWrapper<>();
            organizationManagerQueryWrapper.in("org_id", orgIds1);
            organizationManagerQueryWrapper.in("account_id", accountIds);
            organizationManagerService.remove(organizationManagerQueryWrapper);
        }
        // 在绑定新的组织信息
        List<StaffOrganization> staffOrganizations = new ArrayList<>(staffIds.size() * organizationIds.size());
        for (StaffDTO staffDTO : list) {
            List<StaffOrganization> staffOrganizations1 = new ArrayList<>(organizationIds.size());
            for (Integer organizationId : organizationIds) {
                StaffOrganization staffOrganization = new StaffOrganization();
                staffOrganization.setStaffId(staffDTO.getId());
                staffOrganization.setAccountId(staffDTO.getAccountId());
                staffOrganization.setOrgId(organizationId);
                staffOrganization.setEnterpriseId(enterpriseId);
                staffOrganizations1.add(staffOrganization);
            }
            staffOrganizations.addAll(staffOrganizations1);
        }
        staffOrganizationService.saveBatch(staffOrganizations);
        return ResultJson.success();
    }

    @Override
    public List<Integer> orgList(StaffQuery staffQuery) {
        return staffDao.orgList(staffQuery);
    }

    @Override
    public ResultJson autoImport(Integer enterpriseId) {
        Enterprise enterprise = enterpriseService.findById(enterpriseId);
        if (null == enterprise) {
            return ResultJson.fail("企业不存在");
        }
        AccountQuery accountQuery = new AccountQuery();
        accountQuery.setEnterpriseIdList(Arrays.asList(enterpriseId));
        List<Account> accountList = accountService.getAccountList(null, accountQuery);
        log.info("当前企业 {} 查询到帐号 {} 个", enterpriseId, accountList.size());
        if (accountList.isEmpty()) {
            return ResultJson.fail("没有帐号");
        }
        List<Account> importAccount = new ArrayList<>();
        for (Account account : accountList) {
            List<Role> roleListByAccountId = roleService.getRoleListByAccountId(account.getId());
            if (!roleListByAccountId.isEmpty()) {
                for (Role role : roleListByAccountId) {
                    if (role.getGrade() != BusinessType.INDUSTRY.code) {
                        importAccount.add(account);
                        break;
                    }
                }
            }
        }
        if (importAccount.isEmpty()) {
            return ResultJson.fail("当前企业下没有符合的员工角色");
        }
        log.info("筛选出企业员工 {} 个", importAccount.size());
        // 去掉已经关联了员工信息的
        List<Integer> accountIds = importAccount.stream().map(i -> i.getId()).collect(Collectors.toList());
        QueryWrapper<StaffOrganization> staffQueryWrapper = new QueryWrapper<>();
        staffQueryWrapper.in("account_id", accountIds);
        List<StaffOrganization> staffs = staffOrganizationService.list(staffQueryWrapper);
        if (!staffs.isEmpty()) {
            List<Integer> existStaff = staffs.stream().map(i -> i.getAccountId()).distinct().collect(Collectors.toList());
            importAccount = importAccount.stream().filter(i -> !existStaff.contains(i.getId())).collect(Collectors.toList());
        }
        if (importAccount.isEmpty()) {
            return ResultJson.fail("暂无未处理的员工");
        }
        // 剩下的就是需要生成员工信息的帐号
        List<Staff> insertList = new ArrayList<>(importAccount.size());
        for (Account account : importAccount) {
            Staff staff = new Staff();
            staff.setAccountId(account.getId());
            staff.setDeleted(false);
            insertList.add(staff);
        }
        saveBatch(insertList);
        // 插入关联企业信息
        List<StaffOrganization> staffOrganizations = new ArrayList<>(insertList.size());
        for (Staff staff : insertList) {
            StaffOrganization staffOrganization = new StaffOrganization();
            staffOrganization.setAccountId(staff.getAccountId());
            staffOrganization.setStaffId(staff.getId());
            staffOrganization.setEnterpriseId(enterpriseId);
            staffOrganization.setOrgId(enterprise.getOrganizationId());
            staffOrganizations.add(staffOrganization);
        }
        staffOrganizationService.saveBatch(staffOrganizations);
        return ResultJson.success("处理完成，共 " + importAccount.size() + " 条");
    }

    @Override
    public StaffDTO one(StaffQuery staffQuery) {
        if (null == staffQuery) {
            log.warn("查询员工参数错误");
            return null;
        }
        Staff staff = staffDao.one(staffQuery);
        if (null == staff) {
            return null;
        }
        return detail(staff.getId(), staffQuery.getEnterpriseId(), null, null);
    }

    @Override
    public List<OrganizationDTO> orgTree(Integer projectId, Integer accountId) {
        if (null == projectId) {
            throw new DataException("参数错误");
        }
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.withProjectIds(Arrays.asList(projectId)).withRoundLevel(-10);
        List<Integer> spaceTypeIds = organizationTypeService.spaceIds();
        organizationQuery.setTypes(spaceTypeIds);
        List<Organization> organizations = organizationService.list(organizationQuery);
        List<OrganizationDTO> organizationDTOS = orgWrapper(organizations);
        // 查询账号关联的组织
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("account_id", accountId);
        accountOrganizationQueryWrapper.in("type", spaceTypeIds);
        List<AccountOrganization> accountOrganizations = accountOrganizationService.list(accountOrganizationQueryWrapper);
        if (CollectionUtils.isNotEmpty(accountOrganizations)) {
            List<Integer> organizationIds = accountOrganizations.stream().map(i -> i.getOrganizationId()).distinct().collect(Collectors.toList());
            for (OrganizationDTO organizationDTO : organizationDTOS) {
                if (organizationIds.contains(organizationDTO.getId())) {
                    organizationDTO.setBind(true);
                }
            }
        }
        return treeMaker(organizationDTOS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson review(Integer recordId, Boolean pass, Integer industryId, Integer currentEnterpriseId) {
        //查询提交记录
        StaffAuditRecord staffAuditRecord = staffAuditRecordService.getById(recordId);
        if (null == staffAuditRecord) {
            throw new DataException("审核记录不存在");
        }
        int status = 0;
        Enterprise enterprise = null;
        if (pass) {
            //查询企业
            enterprise = enterpriseService.getById(staffAuditRecord.getEnterpriseId());
            if (!enterprise.getType().contains(EnterpriseTypeEnum.OPERATOR.id.toString())) {
                //查询运营商配置是否审核入驻企业录入员工
                String reviewChildrenStaff = enterpriseExtraService.get(enterprise.getParentId(), OPERATOR_REVIEW_ATTRIBUTE);
                if ("1".equals(reviewChildrenStaff)) {
                    if (staffAuditRecord.getStatus() == 1) {
                        if (enterprise.getId().equals(currentEnterpriseId)) {
                            status = 2;
                        }
                    }
                    if (staffAuditRecord.getStatus() == 2) {
                        if (enterprise.getParentId().equals(currentEnterpriseId)) {
                            status = 3;
                        }
                    }
                } else {
                    status = 3;
                }
            } else {
                status = 3;

            }
        } else {
            status = 4;
        }
        if (status == 0) {
            throw new BusinessException("操作有误");
        }
        if (staffAuditRecord.getStatus() == status) {
            throw new BusinessException("重复操作");
        }
        staffAuditRecord.setStatus((short) status);
        if(status == 3){
            handlePass(staffAuditRecord,enterprise,industryId);
        }
        staffAuditRecordService.updateById(staffAuditRecord);
        return ResultJson.success();
    }

    @Override
    public Page pageReviewStaff(StaffAuditRecordQuery query, Page page, Integer industryId) {
        List<Role> roles = roleService.list(new QueryWrapper<Role>()
                .eq("industry_id", industryId)
                .in("code", TOURIST_ROLE_CODE, STAFF_ROLE_CODE));
        if(roles.size() == 0){
            page.setTotal(0);
            return page;
        }
        query.setRoleIds(roles.stream().map(Role::getId).collect(Collectors.toList()));
        Page<StaffAuditRecord> staffAuditRecordPage = staffAuditRecordService.page(query, page);
        List<StaffAuditRecord> records = staffAuditRecordPage.getRecords();
        if (records.size() == 0) {
            return staffAuditRecordPage;
        }
        //查询企业
        Enterprise reviewEnterprise = enterpriseService.getById(query.getReviewEnterpriseId());
        if (null == reviewEnterprise) {
            throw new DataException("企业不存在");
        }
        //状态描述
        records.forEach(x -> {
            if (x.getStatus() == 1) {
                x.setStatusDesc("待审核");
                x.setOpenReview(true);
            }
            if (x.getStatus() == 3) {
                x.setStatusDesc("审核通过");
                x.setOpenReview(false);
            }
            if (x.getStatus() == 4) {
                x.setStatusDesc("审核失败");
                x.setOpenReview(false);
            }
        });
        if (!reviewEnterprise.getType().contains(EnterpriseTypeEnum.OPERATOR.id.toString())) {
            //查询运营商
            Enterprise operator = enterpriseService.getById(reviewEnterprise.getParentId());
            //查询运营商是否配置审核入驻企业录入员工
            String value = enterpriseExtraService.get(operator.getId(), OPERATOR_REVIEW_ATTRIBUTE);
            if ("1".equals(value)) {
                records.forEach(x -> {
                    if (query.getCurrentEnterpriseId().equals(query.getReviewEnterpriseId())) {
                        if (x.getStatus() == 1) {
                            x.setStatusDesc("待提交");
                            x.setOpenReview(true);
                        }
                        if (x.getStatus() == 2) {
                            x.setStatusDesc("审核中");
                            x.setOpenReview(false);
                        }
                    } else {
                        if (x.getStatus() == 2) {
                            x.setStatusDesc("待审核");
                            x.setOpenReview(true);
                        }
                    }
                });
            }
        }
        records.forEach(x -> x.setEnterpriseName(reviewEnterprise.getName()));
        return staffAuditRecordPage;
    }

    @Override
    public List<Enterprise> listReviewEnterprise(Integer currentEnterpriseId, String likeEnterpriseName) {
        List<Enterprise> enterprises = new ArrayList<>();
        Enterprise enterprise = enterpriseService.getById(currentEnterpriseId);
        if (enterprise.getType().contains(EnterpriseTypeEnum.OPERATOR.id.toString())) {
            String reviewChildrenStaff = enterpriseExtraService.get(currentEnterpriseId, OPERATOR_REVIEW_ATTRIBUTE);
            if ("1".equals(reviewChildrenStaff)) {
                enterprises = enterpriseService.list(new QueryWrapper<Enterprise>()
                        .eq("parent_id", enterprise.getId())
                );
            }
        }
        enterprises.add(enterprise);
        if (StringUtils.isNotBlank(likeEnterpriseName)) {
            return enterprises.stream()
                    .filter(x -> x.getName().toUpperCase().contains(likeEnterpriseName.toUpperCase()))
                    .collect(Collectors.toList());
        }
        return enterprises;
    }

    private static Map<Integer, String> NOT_REVIEW = new HashMap<Integer, String>() {{
        put(1, "待审核");
    }};

    private static Map<Integer, String> NOT_SUBMIT = new HashMap<Integer, String>() {{
        put(1, "待提交");
    }};

    private static Map<Integer, String> REVIEWING = new HashMap<Integer, String>() {{
        put(2, "审核中");
    }};

    private static Map<Integer, String> REVIEW_PASS = new HashMap<Integer, String>() {{
        put(3, "审核通过");
    }};

    private static Map<Integer, String> REVIEW_FAIL = new HashMap<Integer, String>() {{
        put(4, "审核失败");
    }};

    private static List<Map<Integer, String>> REVIEW_STATUS_3 = Arrays.asList(NOT_REVIEW, REVIEW_PASS, REVIEW_FAIL);

    private static List<Map<Integer, String>> REVIEW_STATUS_4 = Arrays.asList(NOT_SUBMIT, REVIEWING, REVIEW_PASS, REVIEW_FAIL);

    @Override
    public List<JSONObject> reviewStatus(Integer currentEnterpriseId, Integer reviewEnterpriseId) {
        Enterprise enterprise = enterpriseService.getById(currentEnterpriseId);
        //当前企业为供应商
        if (enterprise.getType().contains(EnterpriseTypeEnum.OPERATOR.id.toString())) {
            if (currentEnterpriseId.equals(reviewEnterpriseId)) {
                return processReviewStatus(REVIEW_STATUS_3);
            } else {
                return processReviewStatus(REVIEW_STATUS_4);
            }
        }
        String value = enterpriseExtraService.get(enterprise.getParentId(), OPERATOR_REVIEW_ATTRIBUTE);
        if ("1".equals(value)) {
            return processReviewStatus(REVIEW_STATUS_4);
        }
        return processReviewStatus(REVIEW_STATUS_3);
    }

    private List<JSONObject> processReviewStatus(List<Map<Integer, String>> list) {
        return list.stream().map(x -> {
            JSONObject jsonObject = new JSONObject();
            x.keySet().forEach(key -> {
                        jsonObject.put("value", key);
                        jsonObject.put("label", x.get(key));
                    }
            );
            return jsonObject;
        }).collect(Collectors.toList());
    }

    @Override
    public ResultJson batchReview(List<Integer> recordIds, Boolean pass, Integer industryId, Integer currentEnterpriseId) {
        Executor executor = SpringContextUtils.getBean(Executor.class);
        IStaffService staffService = SpringContextUtils.getBean(IStaffService.class);
        List<Integer> failIds = new ArrayList<>();
        CountDownLatch countDownLatch = new CountDownLatch(recordIds.size());
        recordIds.forEach(x -> CompletableFuture.runAsync(() -> {
            try {
                staffService.review(x, pass, industryId, currentEnterpriseId);
            } catch (Exception e) {
                log.error("记录ID:{} 审核异常{}", x, e);
                failIds.add(x);
            } finally {
                countDownLatch.countDown();
            }
        }, executor));
        if (failIds.size() == 0) {
            return ResultJson.success();
        }
        return ResultJson.fail(failIds.stream().map(Object::toString).collect(Collectors.joining(",")) + "审核异常");
    }

    @Override
    public JSONObject reviewDetail(Integer recordId, Integer industryId, Integer currentEnterpriseId) {
        StaffAuditRecord record = staffAuditRecordService.getById(recordId);
        if (null != record) {
            Enterprise enterprise = enterpriseService.getById(record.getEnterpriseId());
            //开启审核按钮
            if (enterprise.getType().contains(EnterpriseTypeEnum.OPERATOR.id.toString())) {
                record.setOpenReview(record.getStatus() == 1);
            }else{
                //查询运营商
                Enterprise operator = enterpriseService.getById(enterprise.getParentId());
                //查询运营商是否配置审核入驻企业录入员工
                String value = enterpriseExtraService.get(operator.getId(), OPERATOR_REVIEW_ATTRIBUTE);
                if ("1".equals(value)) {
                    if(enterprise.getId().equals(currentEnterpriseId)){
                        record.setOpenReview(record.getStatus() == 1);
                    }else {
                        record.setOpenReview(record.getStatus() == 2);
                    }
                } else {
                    record.setOpenReview(record.getStatus() == 1);
                }
            }
            record.setEnterpriseName(enterprise.getName());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("staff", record);
            if (record.getStatus() == 1 || record.getStatus() == 4) {
                return jsonObject;
            }
            JSONObject permission = new JSONObject();
            //查询角色权限
            if (record.getStatus() == 3) {
                List<AccountRole> accountRoles = accountRoleService.list(new QueryWrapper<AccountRole>()
                        .eq("account_id", record.getAccountId()));
                if (accountRoles.size() > 0) {
                    List<Integer> roleIds = accountRoles.stream().map(AccountRole::getRoleId).distinct().collect(Collectors.toList());
                    List<Role> roles = roleService.list(new QueryWrapper<Role>()
                            .in("id", roleIds)
                            .and(x -> x.eq("industry_id", industryId).or().eq("enterprise_id", record.getEnterpriseId())));
                    permission.put("roles", roles);
                }
            }
            if (record.getStatus() == 2) {
                Role staffRole = roleService.getOne(new QueryWrapper<Role>()
                        .eq("industry_id", industryId)
                        .eq("code", STAFF_ROLE_CODE));
                permission.put("roles", Collections.singletonList(staffRole));
            }
            //查询空间权限
            List<EnterpriseSpace> enterpriseSpaces = enterpriseSpaceService.list(new QueryWrapper<EnterpriseSpace>()
                    .eq("enterprise_id", record.getEnterpriseId()));
            if (enterpriseSpaces.size() > 0) {
                List<Integer> organizationIds = enterpriseSpaces.stream()
                        .map(EnterpriseSpace::getOrganizationId).distinct().collect(Collectors.toList());
                List<Organization> organizations = organizationService.list(new QueryWrapper<Organization>()
                        .in("id", organizationIds)
                        .eq("project_id", record.getProjectId()));
                String space = organizations.stream().sorted(Comparator.comparingInt(Organization::getId))
                        .map(Organization::getName)
                        .collect(Collectors.joining("-"));
                permission.put("space", space);
            }
            //查询项目权限
            Project project = projectService.getById(record.getProjectId());
            permission.put("project", project);
            jsonObject.put("permission", permission);
            return jsonObject;
        }
        return null;
    }

    private void handlePass(StaffAuditRecord staffAuditRecord, Enterprise enterprise, Integer industryId) {
        StaffDTO staffDTO = new StaffDTO();
        BeanUtils.copyProperties(staffAuditRecord, staffDTO);
        staffDTO.setId(null);
        staffDTO.setEnterpriseId(Collections.singletonList(staffAuditRecord.getEnterpriseId()));
        staffDTO.setProjectIds(Collections.singletonList(staffAuditRecord.getProjectId()));
        //dataConvert(staffDTO);
        //查询账号
        Account account = accountService.getById(staffAuditRecord.getAccountId());
        if (null == account) {
            throw new DataException("账号不存在");
        }
        //去除密码
        account.setPassword(null);
        //填充名称
        account.setName(staffAuditRecord.getName());
        // 账号设置身份证号码
        if (CredentialsEnum.ID_CARD == staffDTO.getCardType()) {
            account.setIdCard(staffDTO.getCardNo());
        }
        //查询账号角色
        List<Role> dbRoles = roleService.getRoleListByAccountId(account.getId());
        List<Role> roles = dbRoles.stream()
                .filter(x -> {
                    //过滤业态角色 删除游客角色
                    if (x.getIndustryId() != null) {
                        return x.getIndustryId() == industryId.intValue() && !TOURIST_ROLE_CODE.equals(x.getCode());
                    }
                    //过滤企业角色
                    if (x.getEnterpriseId() != null) {
                        return x.getEnterpriseId() == enterprise.getId().intValue();
                    }
                    return false;
                })
                .collect(Collectors.toList());
        //查询员工角色
        Role staffRole = roleService.getOne(new QueryWrapper<Role>()
                .eq("industry_id", industryId)
                .eq("code", STAFF_ROLE_CODE));
        if (null == staffRole) {
            throw new DataException("员工角色不存在");
        }
        //增加员工角色
        roles.add(staffRole);
        //权限组
        PermissionGroupDTO permissionGroupDTO = new PermissionGroupDTO();
        permissionGroupDTO.setAccountId(account.getId());
        permissionGroupDTO.setRoleIds(roles.stream().map(x -> x.getId().toString()).distinct().collect(Collectors.joining(",")));
        permissionGroupDTO.setRoleList(roles.stream().map(Role::getId).collect(Collectors.toList()));
        permissionGroupDTO.setProjectList(Collections.singletonList(staffAuditRecord.getProjectId()));
        //修改账号
        AccountRelation accountRelation = new AccountRelation();
        //当前业态ID
        accountRelation.setCurrentIndustryId(industryId);
        //企业ID
        accountRelation.setEnterpriseIds(Collections.singletonList(staffAuditRecord.getEnterpriseId()));
        //项目ID
        accountRelation.setProjectIds(Collections.singletonList(staffAuditRecord.getProjectId()));
        //角色ID列表
        accountRelation.setRoleIds(roles.stream().map(Role::getId).collect(Collectors.toList()));
        accountService.updateAccountV2(account, account, accountRelation, Collections.singletonList(permissionGroupDTO));
        //查询组织
        Organization organization = organizationService.getById(enterprise.getOrganizationId());
        if (null == organization) {
            throw new DataException("组织不存在");
        }
        staffDTO.setOrgIds(Collections.singletonList(organization.getId()));
        //保存员工信息和业务类型的关系
        Staff staff = saveStaff(staffDTO, account.getId());
        //保存人脸到人脸库
        if (null != staffDTO.getProjectId() && StringUtils.isNotEmpty(staffDTO.getFaceUrl())) {
            saveFace(staff.getAccountId(), staffDTO);
        }
        //保存组织信息
        saveOrganization(staffDTO, account, staff);
        //保存空间信息
        //updateAccountOrganization(staff.getAccountId(), staffDTO.getSpaceIds());
        staffDTO.setAccountId(account.getId());
        staffDTO.setId(staff.getId());
        //保存自定义字段
        //saveStaffExtra(staffDTO);
        try {
            staffProducer.create(staffDTO);
        } catch (Exception e) {
            log.info("当前员工数据推送到新增主题异常,员工数据={}", staffDTO);
        }
    }


    private List<OrganizationDTO> treeMaker(List<OrganizationDTO> organizations) {
        if (organizations.isEmpty()) {
            return Collections.emptyList();
        }
        List<OrganizationDTO> sort = organizations.stream().distinct().sorted(Comparator.comparing(Organization::getLevel)).collect(Collectors.toList());
        // get top element
        OrganizationDTO organization = sort.get(0);
        List<OrganizationDTO> tops = sort.stream().parallel().filter(s -> organization.getLevel() == s.getLevel()).collect(Collectors.toList());

        // 过滤掉根节点，剩余子节点
        List<OrganizationDTO> nodes = organizations.stream().parallel()
                .filter(o -> !tops.stream().map(Organization::getId).collect(Collectors.toList()).contains(o.getId()))
                .collect(Collectors.toList());
        nodes.stream().forEach(organizationDTO -> organizationDTO.setChildren(this.listChildren(nodes, organizationDTO.getId())));
        return nodes;
    }

    private List<OrganizationDTO> orgWrapper(List<Organization> tops) {
        // 封装根节点数据
        return tops.stream().map(o -> {
            OrganizationDTO organizationDTO = new OrganizationDTO();
            BeanUtils.copyProperties(o, organizationDTO);
            StringBuilder sbd = new StringBuilder();
            sbd.append(o.getId()).append("-").append(o.getName());
            organizationDTO.setKeywords(sbd.toString());
            organizationDTO.setUniqueKey((o.getProjectId() == null ? "#" : o.getProjectId()) + "-" + o.getId() + "-" + o.getName());
            return organizationDTO;
        }).collect(Collectors.toList());
    }

    /**
     * 筛选子节点
     *
     * @param organizations 总集合
     * @param parentId
     * @return
     */
    private List<OrganizationDTO> listChildren(List<OrganizationDTO> organizations, Integer parentId) {

        if (null == organizations || organizations.isEmpty()) {
            return Collections.emptyList();
        }
        // 过滤出子节点
        List<OrganizationDTO> organizationList = organizations.stream().parallel()
                .filter(organization -> organization.getParentId().equals(parentId)).distinct()
                .collect(Collectors.toList());
        // 移除处理节点
        organizations.removeAll(organizationList);
        // 封装子节点
        return organizationList.stream().map(organization -> {
            organization.setChildren(this.listChildren(organizations, organization.getId()));
            return organization;
        }).collect(Collectors.toList());
    }

    /**
     * 保存员工信息
     *
     * @param staffDTO
     * @param accountId
     * @return
     */
    private Staff saveStaff(StaffDTO staffDTO, Integer accountId) {
        Staff staff = new Staff();
        BeanUtils.copyProperties(staffDTO, staff);
        staff.setAccountId(accountId);
        staff.setDeleted(false);
        if (null != staffDTO.getId()) {
            staffDao.updateById(staff);
        } else {
            staffDao.insert(staff);
        }
        // 保存员工和业务类型的关联关系 先删除 后新增
        QueryWrapper<StaffBusinessRelation> staffBusinessRelationQueryWrapper = new QueryWrapper<>();
        staffBusinessRelationQueryWrapper.eq("staff_id", staff.getId());
        staffBusinessRelationService.remove(staffBusinessRelationQueryWrapper);
        if (CollectionUtils.isNotEmpty(staffDTO.getBusinessIds())) {
            List<StaffBusinessType> staffBusinessTypes = businessTypeDao.selectBatchIds(staffDTO.getBusinessIds());
            if (CollectionUtils.isNotEmpty(staffBusinessTypes)) {
                List<Integer> businessTypeIds = staffBusinessTypes.stream().map(i -> i.getId()).collect(Collectors.toList());
                List<StaffBusinessRelation> staffBusinessRelations = new ArrayList<>(businessTypeIds.size());
                for (Integer businessTypeId : businessTypeIds) {
                    StaffBusinessRelation staffBusinessRelation = new StaffBusinessRelation();
                    staffBusinessRelation.setBusinessId(businessTypeId);
                    staffBusinessRelation.setStaffId(staff.getId());
                    staffBusinessRelations.add(staffBusinessRelation);
                }
                staffBusinessRelationService.saveBatch(staffBusinessRelations);
            }
        }
        return staff;
    }

    /**
     * 1获取组织信息 2获取空间信息
     *
     * @param id           员工id
     * @param enterpriseId 企业id
     * @param staffDTO
     */
    private void getOrganizationInfo(Integer id, Integer enterpriseId, StaffDTO staffDTO) {
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.eq("staff_id", id);
        List<StaffOrganization> list = staffOrganizationService.list(staffOrganizationQueryWrapper);
        if (list.isEmpty()) {
            throw new DataException("数据错误，该员工暂未关联组织");
        }
        List<Integer> orgIds = list.stream().map(i -> i.getOrgId()).collect(Collectors.toList());
        // 获取当前企业下组织信息
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.select("id", "name");
        if (null == enterpriseId) {
            throw new DataException("缺少企业信息");
        }
        organizationQueryWrapper.eq("enterprise_id", enterpriseId);
        organizationQueryWrapper.in("id", orgIds);
        List<Organization> list1 = organizationService.list(organizationQueryWrapper);
        if (!list1.isEmpty()) {
            staffDTO.setOrgIds(list1.stream().map(i -> i.getId()).collect(Collectors.toList()));
            OrganizationQuery organizationQuery = new OrganizationQuery();
            organizationQuery.withIds(staffDTO.getOrgIds());
            organizationQuery.withRoundLevel(10);
            organizationQuery.withTypes(Arrays.asList(OrganizationTypeEnum.ENTERPRISE.id.intValue(), OrganizationTypeEnum.ORG.id.intValue(), OrganizationTypeEnum.PROJECT.id.intValue()));
            Map<Integer, String> map = organizationService.batchFullName(organizationQuery);
            List<Organization> list2 = organizationService.list(organizationQuery);
            List<String> orgNames = map.entrySet().stream().map(i -> {
                String str = "";
                if (null != i.getValue()) {
                    String[] splitStr = i.getValue().split("-");
                    str = splitStr[splitStr.length -1];
                }
                return str;
            }).collect(Collectors.toList());
            staffDTO.setOrgNames(orgNames);
            staffDTO.setParentOrgs(list2);
            staffDTO.setOrganizations(list1);
        }

        /**
         * 设置改帐号的空间信息
         */
        getSpaceInfo(enterpriseId, staffDTO);
    }


    private void getSpaceInfo(Integer enterpriseId, StaffDTO staffDTO) {
        Integer accountId = staffDTO.getAccountId();
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("account_id", accountId);
        accountOrganizationQueryWrapper.in("type", organizationTypeService.spaceIds());
        accountOrganizationQueryWrapper.eq("enterprise_id", enterpriseId);
        List<AccountOrganization> list = accountOrganizationService.list(accountOrganizationQueryWrapper);
        if (CollectionUtils.isNotEmpty(staffDTO.getProjectIds())) {
            List<Organization> orgs = new ArrayList<>();
            Map<Integer, List<Organization>> projectSpaceMap = new HashMap<>();
            if (!list.isEmpty()) {
                List<Integer> collect = list.stream().map(i -> i.getOrganizationId()).distinct().collect(Collectors.toList());
                orgs = organizationService.listByIds(collect);
                projectSpaceMap = orgs.stream().collect(Collectors.groupingBy(Organization::getProjectId, Collectors.toList()));
                staffDTO.setSpaceIds(collect);
            }
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.select("id", "name");
            projectQueryWrapper.in("id", staffDTO.getProjectIds());
            List<Project> projects = projectDao.selectList(projectQueryWrapper);
            Map<Integer, String> proMap = projects.stream().collect(Collectors.toMap(Project::getId, Project::getName));
            List<ProjectSpaceDTO> projectSpaceDTOS = new ArrayList<>(staffDTO.getProjectIds().size());
            for (Integer projectId : staffDTO.getProjectIds()) {
                ProjectSpaceDTO p = new ProjectSpaceDTO();
                p.setProjectId(projectId);
                p.setProjectName(proMap.get(projectId));
                p.setSpaces(projectSpaceMap.get(projectId));
                projectSpaceDTOS.add(p);
            }
            staffDTO.setSpaceInfo(projectSpaceDTOS);
        }
    }

    /**
     * 获取项目
     *
     * @param accountId    帐号id
     * @param enterpriseId 企业id
     * @param staffDTO
     */
    private void getProject(Integer accountId, Integer enterpriseId, StaffDTO staffDTO) {
        QueryWrapper<AccountProject> accountProjectQueryWrapper = new QueryWrapper<>();
        accountProjectQueryWrapper.eq("account_id", accountId);
        List<AccountProject> accountProjects = accountProjectService.list(accountProjectQueryWrapper);
        if (accountProjects.isEmpty()) {
            log.warn("数据错误，该员工暂未关联项目信息");
            return;
        }
        List<Integer> projectIds = accountProjects.stream().map(i -> i.getProjectId()).collect(Collectors.toList());
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.setIds(projectIds);
//        projectQuery.setEnterpriseId(enterpriseId);
        List<Project> list = projectService.list(projectQuery, null);
        if (list.isEmpty()) {
            log.warn("数据错误，该员工暂未关联项目信息");
            return;
        }
        staffDTO.setProjectNames(list.stream().map(i -> i.getName()).collect(Collectors.toList()));
        staffDTO.setProjectIds(list.stream().map(i -> i.getId()).collect(Collectors.toList()));
    }

    /**
     * 获取角色
     *
     * @param accountId    帐号id
     * @param enterpriseId 企业id
     * @param staffDTO
     */
    private void getRole(Integer accountId, Integer enterpriseId, StaffDTO staffDTO) {
        List<Role> roleList = roleService.getRoleListByAccountId(accountId);
        if (roleList.isEmpty()) {
            log.error("数据错误，该员工 帐号 {} 暂在该企业未关联角色信息", accountId);
            return;
        }
        List<Integer> roleIds = new ArrayList<>();
        List<String> names = new ArrayList<>();
        for (Role role : roleList) {
            roleIds.add(role.getId());
            names.add(role.getName());
        }
        staffDTO.setRoleIds(roleIds);
        staffDTO.setRoleNames(names);
    }

    /**
     * 关联权限
     *
     * @param accountId
     * @param projectIds
     * @param roleIds
     */
    private void permissionConnect(Integer accountId, List<Integer> projectIds, List<Integer> roleIds) {
        // 关联项目信息
        projectConnect(accountId, projectIds);
        // 关联角色信息
        roleConnect(accountId, roleIds);
    }

    /**
     * 保存组织信息
     *
     * @param staffDTO
     * @param account  关联组织的帐号
     * @param staff    关联组织的员工
     */
    private void saveOrganization(StaffDTO staffDTO, Account account, Staff staff) {
        List<Integer> orgIds = staffDTO.getOrgIds();
        List<Integer> enterpriseIds = staffDTO.getEnterpriseId();
        Integer enterpriseId = enterpriseIds.get(0);
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.select("id");
        organizationQueryWrapper.in("id", orgIds);
        organizationQueryWrapper.in("enterprise_id", enterpriseId);
        List<Organization> organizations = organizationService.list(organizationQueryWrapper);
        if (organizations.isEmpty()) {
            throw new BusinessException("组织信息不存在");
        }
        // 帐号绑定企业
        handlerAccountEnterprise(account, staffDTO);
        List<Integer> exOrgIds = organizations.stream().map(i -> i.getId()).collect(Collectors.toList());
        // 移除之前的组织
        QueryWrapper<StaffOrganization> staffOrganizationQueryWrapper = new QueryWrapper<>();
        staffOrganizationQueryWrapper.eq("staff_id", staff.getId());
        staffOrganizationQueryWrapper.eq("enterprise_id", enterpriseId);
        //原先组织ids
        List<Integer> orgIds1 = staffOrganizationService.list(staffOrganizationQueryWrapper).stream().distinct().map(i -> i.getOrgId()).collect(Collectors.toList());
        staffOrganizationService.remove(staffOrganizationQueryWrapper);
        //过滤编辑之后的组织
        orgIds1.removeAll(exOrgIds);
        if (CollectionUtils.isNotEmpty(orgIds1)) {
            //是否是之前组织负责人，是则移除身份
            QueryWrapper<OrganizationManager> organizationManagerQueryWrapper = new QueryWrapper<>();
            organizationManagerQueryWrapper.in("org_id", orgIds1);
            organizationManagerQueryWrapper.eq("account_id", staffDTO.getAccountId());
            organizationManagerService.remove(organizationManagerQueryWrapper);
        }
        List<StaffOrganization> staffOrganizations = new ArrayList<>(exOrgIds.size());
        for (Integer exOrgId : exOrgIds) {
            StaffOrganization staffOrganization = new StaffOrganization();
            staffOrganization.setAccountId(account.getId());
            staffOrganization.setStaffId(staff.getId());
            staffOrganization.setOrgId(exOrgId);
            staffOrganization.setEnterpriseId(enterpriseId);
            staffOrganizations.add(staffOrganization);
        }
        staffOrganizationService.saveBatch(staffOrganizations);
    }

    /**
     * 帐号与企业关联
     * @param account
     * @param staffDTO
     */
    private void handlerAccountEnterprise(Account account, StaffDTO staffDTO) {
        Integer enterpriseId = staffDTO.getEnterpriseId().get(0);
        Enterprise enterprise = enterpriseService.getById(enterpriseId);
        if(null ==  enterprise){
            throw new DataException("企业不存在");
        }
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("enterprise_id", enterpriseId);
        accountOrganizationQueryWrapper.eq("account_id", account.getId());
        accountOrganizationQueryWrapper.eq("type", OrganizationTypeEnum.ENTERPRISE.id);
        AccountOrganization one = accountOrganizationService.getOne(accountOrganizationQueryWrapper);
        if(null == one){
            // 创建该帐号与企业的关联关系
            AccountOrganization accountOrganization = new AccountOrganization();
            accountOrganization.setAccountId(account.getId());
            accountOrganization.setOrganizationId(enterprise.getOrganizationId());
            accountOrganization.setEnterpriseId(enterpriseId);
            accountOrganization.setType(OrganizationTypeEnum.ENTERPRISE.id.intValue());
            accountOrganizationService.save(accountOrganization);
        }
    }

    // 绑定项目
    private void projectConnect(Integer accountId, List<Integer> projectIds) {
        ProjectQuery projectQuery = new ProjectQuery();
        if(CollectionUtils.isEmpty(projectIds)){
            log.info("暂无项目绑定需要");
            return;
        }
        List<Project> projectList = projectService.list(projectQuery.withIdList(projectIds), null);
        if (projectList.isEmpty()) {
            throw new BusinessException("项目不存在");
        }
        Integer enterpriseId = projectList.get(0).getEnterpriseId();
        List<Integer> orgIds = projectList.stream().map(i -> i.getId()).collect(Collectors.toList());
        List<Integer> projectIds1 = projectList.stream().map(i -> i.getId()).collect(Collectors.toList());
        QueryWrapper<AccountOrganization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.in("organization_id", orgIds);
        organizationQueryWrapper.eq("account_id", accountId);
        List<AccountOrganization> list = accountOrganizationService.list(organizationQueryWrapper);
        if (!list.isEmpty()) {
            orgIds.remove(list.stream().map(i -> i.getOrganizationId()).collect(Collectors.toList()));
        }
        List<AccountOrganization> accountOrganizations = new ArrayList<>(orgIds.size());
        for (Integer orgId : orgIds) {
            AccountOrganization accountOrganization = new AccountOrganization();
            accountOrganization.setOrganizationId(orgId);
            accountOrganization.setEnterpriseId(enterpriseId);
            accountOrganization.setAccountId(accountId);
            accountOrganizations.add(accountOrganization);
        }
        accountOrganizationService.saveBatch(accountOrganizations);
        QueryWrapper<AccountProject> accountProjectQueryWrapper = new QueryWrapper<>();
        accountProjectQueryWrapper.in("project_id", projectIds1);
        accountProjectQueryWrapper.eq("account_id", accountId);
        List<AccountProject> list1 = accountProjectService.list(accountProjectQueryWrapper);
        if (!list1.isEmpty()) {
            projectIds1.removeAll(list1.stream().map(i -> i.getProjectId()).collect(Collectors.toList()));
        }
        List<AccountProject> accountProjects = new ArrayList<>(projectIds1.size());
        for (Integer integer : projectIds1) {
            AccountProject accountProject = new AccountProject();
            accountProject.setAccountId(accountId);
            accountProject.setProjectId(integer);
            accountProjects.add(accountProject);
        }
        accountProjectService.saveBatch(accountProjects);
    }

    /**
     * 关联角色信息
     *
     * @param accountId
     * @param roleIds
     */
    private void roleConnect(Integer accountId, List<Integer> roleIds) {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.select("id");
        roleQueryWrapper.in("id", roleIds);
        List<Role> list = roleService.list(roleQueryWrapper);
        List<Integer> roleIns = list.stream().map(i -> i.getId()).collect(Collectors.toList());
        if (list.isEmpty()) {
            throw new DataException("角色不存在");
        }
        QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
        accountRoleQueryWrapper.eq("account_id", accountId);
        accountRoleQueryWrapper.in("role_id", list.stream().map(i -> i.getId()).collect(Collectors.toList()));
        List<AccountRole> list1 = accountRoleService.list(accountRoleQueryWrapper);
        if (!list1.isEmpty()) {
            roleIns.removeAll(list1.stream().map(i -> i.getRoleId()).collect(Collectors.toList()));
        }
        List<AccountRole> accountRoles = new ArrayList<>(roleIns.size());
        for (Integer roleIn : roleIns) {
            AccountRole accountRole = new AccountRole();
            accountRole.setAccountId(accountId);
            accountRole.setRoleId(roleIn);
            accountRoles.add(accountRole);
        }
        accountRoleService.saveBatch(accountRoles);
    }

    /**
     * 员工数据检查
     *
     * @param staffDTO
     * @param operator
     * @param isBind   是否是关联操作
     * @return
     */
    private ResultJson staffCheck(StaffDTO staffDTO, Account operator, boolean isBind) {
        if (null == staffDTO) {
            return ResultJson.fail("参数错误");
        }
        if (StringUtils.isEmpty(staffDTO.getName())) {
            return ResultJson.fail("姓名必须填写");
        } else {
            if (20 < staffDTO.getName().length()) {
                return ResultJson.fail("请输入20个字符以内的姓名");
            }
        }
        if (StringUtils.isEmpty(staffDTO.getPhone())) {
            return ResultJson.fail("手机号必须填写");
        } else {
            if (!ValidatorUtil.isMobile(staffDTO.getPhone())) {
                return ResultJson.fail("请输入正确的手机号");
            }
        }
        if (staffDTO.getId() == null) {
            // 新增
            if (StringUtils.isEmpty(staffDTO.getPassword())) {
                return ResultJson.fail("密码必须填写");
            } else {
                if (!ValidatorUtil.isPassword(staffDTO.getPassword())) {
                    return ResultJson.fail("密码格式错误");
                }
            }
        } else {
            // 修改
            if (StringUtils.isNotEmpty(staffDTO.getPassword()) && !ValidatorUtil.isPassword(staffDTO.getPassword())) {
                return ResultJson.fail("密码格式错误");
            }
        }

        if (StringUtils.isEmpty(staffDTO.getLoginName())) {
            staffDTO.setLoginName(UUID.randomUUID().toString().replaceAll("-", "").substring(0,20));
        } else {
            if (3 > staffDTO.getLoginName().length() || 20 < staffDTO.getLoginName().length()) {
                return ResultJson.fail("用户名格式错误");
            }
        }
        if (StringUtils.isNotEmpty(staffDTO.getEmail())) {
            if (!ValidatorUtil.isEmail(staffDTO.getEmail())) {
                return ResultJson.fail("邮箱格式错误");
            }
        }
        if (CollectionUtils.isEmpty(staffDTO.getOrgIds())) {
            return ResultJson.fail("请选择组织");
        }
//        if (CollectionUtils.isEmpty(staffDTO.getProjectIds())) {
//            return ResultJson.fail("请选择管理项目");
//        }
        if (CollectionUtils.isEmpty(staffDTO.getRoleIds())) {
            return ResultJson.fail("请选择关联角色");
        }
        if (null == staffDTO.getEnterpriseId()) {
            return ResultJson.fail("缺少企业信息");
        }
        // 帐号（用户名）重复不让添加
        if (null == staffDTO.getId() && !isBind) {
            Account originalAccount = accountService.findByLoginName(staffDTO.getLoginName(), operator.getIndustryId());
            if (null != originalAccount) {
                return ResultJson.fail("帐号已存在，请勿重复添加");
            }
        }

        // 工号企业唯一
        if (StringUtils.isNotEmpty(staffDTO.getWorkCode())) {
            if (null != staffDTO.getId()) {
                // 修改
                /*StaffQuery staffQuery = new StaffQuery();
                staffQuery.setEnterpriseId(staffDTO.getEnterpriseId().get(0));
                staffQuery.setWorkCodes(Arrays.asList(staffDTO.getWorkCode()));
                List<StaffDTO> list = staffDao.list(staffQuery);*/
                //全局唯一校验
                QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("work_code", staffDTO.getWorkCode());
                List<Staff> list = staffDao.selectList(queryWrapper);
                list = list.stream().filter(i -> i.getId().intValue() != staffDTO.getId().intValue()).collect(Collectors.toList());
                if (!list.isEmpty()) {
                    return ResultJson.fail("工号已存在");
                }
            } else {
                // 新增
                /*StaffQuery staffQuery = new StaffQuery();
                staffQuery.setEnterpriseId(staffDTO.getEnterpriseId().get(0));
                staffQuery.setWorkCodes(Arrays.asList(staffDTO.getWorkCode()));
                List<StaffDTO> list = staffDao.list(staffQuery);*/
                //全局唯一校验
                QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("work_code", staffDTO.getWorkCode());
                List<Staff> list = staffDao.selectList(queryWrapper);
                if (!list.isEmpty()) {
                    return ResultJson.fail("工号已存在");
                }
            }

        }
        if (CredentialsEnum.ID_CARD == staffDTO.getCardType() && !com.xhwl.common.utils.ValidatorUtil.isIDCard(staffDTO.getCardNo())) {
            return ResultJson.fail("身份证号格式错误");
        }
        if (!staffDTO.getPermissionGroupDTOs().isEmpty()){
            for (PermissionGroupDTO permissionGroupDTO : staffDTO.getPermissionGroupDTOs()){
                if (null == permissionGroupDTO.getEnterpriseId()){
                    permissionGroupDTO.setEnterpriseId(staffDTO.getEnterpriseId().get(0));
                }
            }
        }
        return ResultJson.success();
    }

    @Override
    public Staff findByWorkCode(String workCode) {
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_code", workCode);
        List<Staff> list = staffDao.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(list)){
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<StaffDTO>  findByEntIds(List<Integer> entIds) {
        if(CollectionUtils.isEmpty(entIds)){
            return null;
        }
        List<StaffDTO> list = staffDao.findByEntIds(entIds);
        //添加账号信息
        accountInfoSetter(list);
        return list;
    }

    @Override
    public List<StaffDTO> findByOrgIds(List<Integer> orgIds) {
        if(CollectionUtils.isEmpty(orgIds)){
            return null;
        }
        List<StaffDTO> list = staffDao.findByOrgIds(orgIds);
        //添加账号信息
        accountInfoSetter(list);
        return list;
    }

    @Override
    public List<Integer> findAccountId(List<Integer> ids, Integer type) {
        if(CollectionUtils.isEmpty(ids) && type != null){
            return null;
        }
        List<Integer> list = staffDao.findAccountId(ids,type);
        return list;
    }


}

